[MongoDB] How to resolve SyntaxError: Unexpected end of input, Unexpected token }

Tadashi Shigeoka ·  Tue, February 26, 2019

This article introduces how to resolve SyntaxError: Unexpected end of input and SyntaxError: Unexpected token } error messages that occur in MongoDB shell.

MongoDB | モンゴディービー

Cases where SyntaxError occurs

Here’s a sample MongoDB query code that causes SyntaxError.

MongoDB query

var sampleFunc = function(str){
  var result = str.replace(/\"+/g, '');
  return result;
}

Execution result

mongodb> var sampleFunc = function(str){
...   var str = 'a"b"c';
...   var result = str.replace(/\"+/g, '');
2019-02-26T13:30:21.665+0000 E QUERY    SyntaxError: Unexpected end of input
mongodb> }
2019-02-26T13:30:21.669+0000 E QUERY    SyntaxError: Unexpected token }

By the way, function definition

function sampleFunc (str){
  var result = str.replace(/\"+/g, '');
  return result;
}

Cases where SyntaxError does not occur

Not using regex literals inside functions

When not using regex literals containing double quotes ” like /”+/g inside functions, SyntaxError did not occur.

var str = 'a"b"c';
var result = str.replace(/\"+/g, '');

String.prototype.replace()

Since the double quotes ” specified in the pattern part of the regex literal /pattern/flags seem to be the cause, rewriting the code to use constructor notation RegExp resolved the error.

var sampleFunc = function(str){
  var result = str.replace(new RegExp('"+', 'g'), '');
  return result;
}

What causes SyntaxError?

This time, the double quotes ” were the cause, but the error-prone code worked normally in Node.js repl. I think “there’s probably an issue with MongoDB repl processing”, but I haven’t examined the code in detail.

That’s all from the Gemba.

References