我有以下代码:
var objectid = infos[i].id;
var name = infos[i].name;
return collection.aggregate([
{$match: {app: new ObjectId(objectid)}},
{$group: {_id: "$uid", amt: {$sum: 1}}}
])
以前这段代码工作正常,但最近我开始在帆中获得以下堆栈跟踪:
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)
由于我导入的ObjectId
如此抱怨:
var ObjectId = require('mongodb').ObjectID;
正如我之前所说的,这种方法很好但不再适用。我真的很困惑。如果我将objectId作为字符串,它将不会返回任何结果。如果我保持原样(因为它之前工作)它会抛出异常。这是什么问题?
我已阅读以下内容:
https://docs.mongodb.com/v3.0/reference/operator/aggregation/cmp/#exp._S_cmp
我能够在robomongo中做到这一点:
db.getCollection("openevent").aggregate([
{$match: {app: new ObjectId(OBJECT_ID) }},
{$group: {_id: "$uid", amt: {$sum: 1}}}
])
使用与上述相同的值。我做错了什么?
我看到sails-mongo
的以下内容:
└─┬ sails-mongo@0.12.1
└─┬ mongodb@2.1.6
└── mongodb-core@1.3.1
答案 0 :(得分:12)
我不知道为什么这甚至是一个答案,但我会发布它。
以前我有这个:
var ObjectId = require('mongodb').ObjectID;
我改为:
var ObjectId = require('sails-mongo/node_modules/mongodb').ObjectID;
不知何故,这一切都有所不同。
答案 1 :(得分:8)
出于后人的考虑,这通常是由于mongo版本之间的兼容性问题。 MongoDB驱动程序2.2使用mongodb-core 2.0(和bson 0.5),而MongoDB驱动程序2.1使用mongodb-core 1.3和bson 0.4。如果您尝试使用带有MongoDB驱动程序2.2的MongoDB驱动程序2.1 ObjectId,您将收到此错误。