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

百般思念 提交于 2019-12-05 04:43:49

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.

profesoralex

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;
Martín Mtz

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);
  }
});

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

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