KVISH KVISH - 4 months ago 219
Node.js Question

Argument must be a string in nodejs

I'm having the following code:

var objectid = infos[i].id;
var name = infos[i].name;
return collection.aggregate([
{$match: {app: new ObjectId(objectid)}},
{$group: {_id: "$uid", amt: {$sum: 1}}}
])


Previously this code was working fine, but recently I started getting the below stacktrace in sails:

error: TypeError: Argument must be a string
at TypeError (native)
at Buffer.write (buffer.js:791:21)
at serializeObjectId (/Users/user/git/pivot/code/node_modules/sails-mongo/node_modules/bson/lib/bson/parser/serializer.js:242:10)
at serializeInto (/Users/user/git/pivot/code/node_modules/sails-mongo/node_modules/bson/lib/bson/parser/serializer.js:699:17)
at serializeObject (/Users/user/git/pivot/code/node_modules/sails-mongo/node_modules/bson/lib/bson/parser/serializer.js:280:18)
at serializeInto (/Users/user/git/pivot/code/node_modules/sails-mongo/node_modules/bson/lib/bson/parser/serializer.js:705:17)
at serializeObject (/Users/user/git/pivot/code/node_modules/sails-mongo/node_modules/bson/lib/bson/parser/serializer.js:280:18)
at serializeInto (/Users/user/git/pivot/code/node_modules/sails-mongo/node_modules/bson/lib/bson/parser/serializer.js:551:17)
at serializeObject (/Users/user/git/pivot/code/node_modules/sails-mongo/node_modules/bson/lib/bson/parser/serializer.js:280:18)
at serializeInto (/Users/user/git/pivot/code/node_modules/sails-mongo/node_modules/bson/lib/bson/parser/serializer.js:705:17)
at serialize (/Users/user/git/pivot/code/node_modules/sails-mongo/node_modules/bson/lib/bson/bson.js:47:27)


It's complaining because of the
ObjectId
which I imported like so:

var ObjectId = require('mongodb').ObjectID;


As I said before, this was working fine but not anymore. I'm really confused. If I put objectId as a string it will not return any results. If I leave it as is (as it was working before) it throws exceptions. What is the issue here?

I have read the below :

https://docs.mongodb.com/v3.0/reference/operator/aggregation/cmp/#exp._S_cmp

I'm able to do this in robomongo:

db.getCollection("openevent").aggregate([
{$match: {app: new ObjectId(OBJECT_ID) }},
{$group: {_id: "$uid", amt: {$sum: 1}}}
])


Using the same values as above. What am I doing wrong??

I see the following for
sails-mongo
:

└─┬ sails-mongo@0.12.1
└─┬ mongodb@2.1.6
└── mongodb-core@1.3.1

Answer

I have no idea why this is even an answer, but I'll post it.

Previously I had this:

var ObjectId = require('mongodb'). ObjectID;

I changed to this:

var ObjectId = require('sails-mongo/node_modules/mongodb').ObjectID;

And somehow that made all the difference.

Comments