Reputation: 67
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?
Upvotes: 0
Views: 544
Reputation: 13369
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
Upvotes: 1