传入的参数必须是24个十六进制字符的字符串-我认为是 [英] Argument passed in must be a string of 24 hex characters - I think it is
问题描述
我有一种方法可以根据其ObjectID在数据库中查找文档:
I have a method to find a document in my database based on its ObjectID:
console.log('id: ' + id + ' type: ' + typeof id);
collection.findOne({'_id':new ObjectID(id)}, function(error,doc) {
if (error) {
callback(error);
} else {
callback(null, doc);
}
});
当我运行它时,出现以下错误:
When I run it I get the following error:
/myPath/node_modules/monk/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/base.js:245
throw message;
^
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at new ObjectID (/myPath/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js:38:11)
at /myPath/collectionDriver.js:134:41
这是指上面的collection.findOne()
行.
在该调用之前,我拥有的控制台日志将id输出为24个十六进制字符的字符串:
The console log I have before that call outputs the id as a string of 24 hex characters:
id: "55153a8014829a865bbf700d" type: string
在此之前,我使用JSON.stringify()
将id从对象转换为字符串,但是它似乎可以正常运行,如console.log中所示.
Before this I convert the id from an object to a string using JSON.stringify()
but it appears to work successfully as shown in my console.log.
在Robomongo中运行db.myCollection.findOne({_id : ObjectId("55153a8014829a865bbf700d")})
会带来预期的结果.
Running db.myCollection.findOne({_id : ObjectId("55153a8014829a865bbf700d")})
in Robomongo brings back the expected result.
推荐答案
在这种情况下,传递给我的函数的ID已经是一个对象ID,因此不需要从中创建新的ObjectID.
The id that was passed in to my function was already an object ID in this case, so did not need a new ObjectID to be created from it.
当ObjectID登录到控制台时,它们显示为十六进制字符串,而不是ObjectID("hexString")
,因此我认为我需要将其转换以进行查找,但是它已经是我需要的格式.
When ObjectIDs are logged out to the console they appear as hex strings, rather than ObjectID("hexString")
, so I thought I needed to convert it to do the find, but it was already in the format that I needed.
这篇关于传入的参数必须是24个十六进制字符的字符串-我认为是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!