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

后端 未结 6 2138
我寻月下人不归
我寻月下人不归 2020-12-18 19:40

I have a method to find a document in my database based on its ObjectID:

      console.log(\'id: \' + id + \' type: \' + typeof id);
      collection.findOne         


        
相关标签:
6条回答
  • 2020-12-18 20:03

    Yeah, I just spent thirty minutes baffled by this. If anyone finds themselves here, first check if you even need to convert to ObjectID in the first place. Like OP, I forgot that the hexstring is logged as just that - a hexstring.

    0 讨论(0)
  • 2020-12-18 20:06

    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;
    
    0 讨论(0)
  • 2020-12-18 20:11

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

    0 讨论(0)
  • 2020-12-18 20:24

    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.

    0 讨论(0)
  • 2020-12-18 20:24

    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);
      }
    });
    
    0 讨论(0)
  • 2020-12-18 20:25

    I was getting this because their was a space in the beginning of the id which I was using in findById method.

    slice(1) removed the empty space and everything worked fine after it.

    var idOfImage = req.params.id;
    Campground.findById(idOfImage.slice(1), function(err, found){
            if(err){
                console.log(err);
            }
            else{
                console.log(found);
                res.render("show", {campground: found});
            }
        });
    
    0 讨论(0)
提交回复
热议问题