Argument passed in must be a string of 24 hex characters - I think it is

微笑、不失礼 提交于 2020-01-02 02:53:15

问题


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

This refers to the collection.findOne() line above.

The console log I have before that call outputs the id as a string of 24 hex characters:

id: "55153a8014829a865bbf700d" type: string

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.

Running db.myCollection.findOne({_id : ObjectId("55153a8014829a865bbf700d")}) in Robomongo brings back the expected result.


回答1:


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.

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.




回答2:


In my case, this worked:

var myId = JSON.parse(req.body.id);
    collection.findOne({'_id': ObjectID(myId)}, function(error,doc) {
    if (error) {
      callback(error);
    } else {
       callback(null, doc);
    }
});

Don't forget to include at the beginning:

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



回答3:


Try this:

var hex = /[0-9A-Fa-f]{6}/g;
id = (hex.test(id))? ObjectId(id) : id;
collection.findOne({'_id':new ObjectID(id)}, function(error,doc) {
  if (error) {
    callback(error);
  } else {
    callback(null, doc);
  }
});



回答4:


Try out ObjectID(id) instead of new ObjectID(id)



来源:https://stackoverflow.com/questions/30051236/argument-passed-in-must-be-a-string-of-24-hex-characters-i-think-it-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!