Search code examples
node.jsmongodbmonk

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


I am having the error : Argument passed in must be a single String of 12 bytes or a string of 24 hex characters. When I tried to use find query using IDs obtained in a previous query. I tried casting them as ObjectIds but it gives me the same error. Your kind help is greatly appreciated. The following is my code:

           var bookIds = []
           for(var j = 0; j < cart.length; j++){
               bookIds.push(cart[j].bookId);
           }
           bookCollection.find({_id:{$in:bookIds}}, {}, function(err, books){
                if(err !== null){
                    console.log(err);
                    res.send({"msg":"Add to cart error"});
                }   
                if(books){
                    console.log("new cart");
                    console.log(cart);
                    console.log(books);
                    res.json(books);
                }
                else{
                    res.send({"msg":"Add to cart error"});
                }
           });

content of cart:

[ { bookId: '5ac5cdf3532808df2e80281e', quantity: 3 },
  { bookId: '5ac5d30479705c2a30a0c235', quantity: 4 },
  { bookId: '5ac5cdfd532808df2e80281f', quantity: 1 },
  { bookId: '5ac5cfe379705c2a30a0c23', quantity: '2' } ]

Solution

  • You don't need to cast them they are already ObjectId when you store them as ObjectId or ref of other model.

    const bookIds = cart.map({bookId} => bookId);
    bookCollection.find({ "_id" :{ "$in": bookIds }})
    .then(books => {
         console.log("new cart");
         console.log(cart);
         console.log(books);
         res.json(books);
    })
    .catch(err => {
         console.log(err);
         res.send({"msg":"Add to cart error"});
    })