0

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?

7
  • How are you providing an array as a URL parameter? Can you show an example of the request URL? Commented Aug 3, 2018 at 22:00
  • @AlanFriedman I add all the ids in a single string then i use .split() to create the array Commented Aug 3, 2018 at 22:14
  • Just asking because it’s unusual to pass an array that way. I’d recommend encoding the array as a query param, or if this endpoint is creating or modifying a resource, sending it in the body of a POST or PUT request. Commented Aug 3, 2018 at 22:22
  • @AlanFriedman You mean something like this: $.get("/index/fill/:id", {ids: arrayWithIds}, function(data){ ... }) ? Commented Aug 3, 2018 at 22:29
  • @BrunoPigatto No, @Alan is speaking about the way you send the ids by url router.get("/index/fill/:id", function(req, res){ which is unusual. Commented Aug 3, 2018 at 22:35

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

try to add in map new ObjectId.createFromHexString(id) and let me know if it works
Same error, ill try to use $.param and see what happens

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.