0

The _id =56aea43cb6be380000616b07; I tried to insert a long string like 56aea43cb6be380000616b07 to the shareids array in mongodb, it always failed "unexpected token illegal".

I tried this straightforward with the mongo command, it has to be '56aea43cb6be380000616b07' to make it work.

But I checked the type of the _id with typeof and it is a string. I tried to set it ObjectID(_id) but still the same. How could I get this through? Thanks.

collection.update({
              "name": name
            }, {
              $push: {
                "shareids": 
                  ObjectID(_id)
              }}, function (err) {
              if (err) {
                console.log("update failed.");
                mongodb.close();
                return callback(err);
              }
zangw
  • 43,869
  • 19
  • 177
  • 214
Chan Austin
  • 2,260
  • 4
  • 14
  • 18
  • How are you defining `_id` as a variable here? Your error message seems to suggest you have emitted the quotes, and in fact it would be another line of code producing the error. Have you even imported `ObjectID` as a function directly? – Blakes Seven Feb 01 '16 at 01:15
  • yes, I did import ObjectID. – Chan Austin Feb 01 '16 at 02:37
  • Hence the error. So you likely need `var ObjectID = require("mongo").ObjectID` to be included in your code to resolve the "unexpected token". – Blakes Seven Feb 01 '16 at 02:39
  • yes, I did import ObjectID.My point is: how to convert 56aea43cb6be380000616b07 to '56aea43cb6be380000616b07'? – Chan Austin Feb 01 '16 at 03:13
  • 1
    As I said earlier, it's meant to be a string, so you need the quotes. Anything without the string quotes would be an "unexpected token". Understand now? – Blakes Seven Feb 01 '16 at 03:22
  • Thanks, Blakes! _id = "'"+_id+"'" should be working for me and was what I after. – Chan Austin Feb 01 '16 at 03:47

1 Answers1

0

The "unexpected token illegal" could be happened with following command.

> db.collection.update({name: 'test'}, {$push: {shareids: ObjectId(56aea43cb6be380000616b
07)}})
2016-02-01T11:34:35.738+0800 SyntaxError: Unexpected token ILLEGAL

However, add quotes to this number as bellow, it will be ok.

> db.collection.update({name: 'test'}, {$push: {shareids: ObjectId('56aea43cb6be380000616
b07')}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
zangw
  • 43,869
  • 19
  • 177
  • 214