mongodb monk - 传入的参数必须是单个 12 字节的字符串或 24 个十六进制字符的字符串

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

我遇到错误:传入的参数必须是一个 12 字节的字符串或 24 个十六进制字符的字符串。当我尝试使用在先前查询中获得的 ID 来使用查找查询时。我尝试将它们转换为 ObjectId,但它给了我同样的错误。非常感谢您的帮助。以下是我的代码:

           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"});
                }
           });

购物车内容:

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

当您将它们存储为其他模型的 ObjectIdref 时,您不需要转换它们,它们已经是 ObjectId

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"});
})

这是因为_id的类型必须是Mongoose.Types.ObjectId

待解决:

objectId = require('mongoose').Types.ObjectId;

 for(var j = 0; j < cart.length; j++){
   bookIds.push(new objectId(cart[j].bookId));
 }