mongdb和尚-传入的参数必须是12个字节的单个字符串或24个十六进制字符的字符串 [英] mongdb monk -Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

查看:74
本文介绍了mongdb和尚-传入的参数必须是12个字节的单个字符串或24个十六进制字符的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

购物车内容:

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

推荐答案

当您将它们存储为 ObjectId 或将它们存储为 ObjectId 或其他型号的ref.

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

这篇关于mongdb和尚-传入的参数必须是12个字节的单个字符串或24个十六进制字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆