简体   繁体   中英

Find() with array of ids not working

I have this route that I access from an AJAX GET call.

router.get("/index/fill/:id", function(req, res){
    var idArray = req.params.id;
    console.log(idArray); // OUTPUT = "4ed3ede8844f0f351100000c", "4ed3f117a844e0471100000d"
    User.find({'_id': {$in: idArray}}, function(err, foundUsers){
        console.log(foundUsers);
    });
});

Before the start of the find proccess the code throws me this error:

Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

But when i use typeof in idArray[i] it says that it is a string.
What am I doing wrong here?

I think this is because your ids should be of type ObjectId(...)

Make sure you have imported ObjectId = require('mongodb').ObjectId;

You can try something like this:

router.get("/index/fill/:id", function (req, res) {
    var idArray = req.params.id;
    idArray = idArray.map(id => ObjectId(id));
    User.find({'_id': {$in: idArray}}, function (err, foundUsers) {
        console.log(foundUsers);
    });
});

or can also check new ObjectId.createFromHexString(id) in the map function if for some reason the straightforward object id creation doesn't work

Regarding the error:

Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

It is thrown because find is expecting some ObjectId structure, which looks something like this: {'_id':'somehexof24char123456789'} but it doesn't find and _id which contains a required string so it throws this error.

I think you can find some documentation here and here about ObjectId

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM