【问题标题】:Mongoose find array with $inMongoose 使用 $in 查找数组
【发布时间】:2014-12-29 07:59:57
【问题描述】:
Team.find({
        '_id': { $in: [
            teamIds
        ] }
    }, function(err, teamData) {
        console.log("teams name  " + teamData);
    });

这段代码给了我们未定义的返回值。但是在 var teamIds 中是这样的:

545646d5f5c1cce828982eb7,
545646d5f5c1cce828982eb8,
54564af5c9ddf61e2b56ad1e,
54564c1f1de201782bcdb623,
54564d2fc660a7e12be6c7a2,
54564df985495f142c638f9f,
54564eadb511f1792c9be138,
54564ec40cf6708a2cd01c81,
54564ee495f4aea22cf23728

有人看到错误吗?

【问题讨论】:

    标签: arrays node.js mongodb mongoose


    【解决方案1】:

    如果teamIds 已经是一个数组,那么你不应该将它包装在另一个数组中:

    Team.find({
        '_id': { $in: teamIds }
    }, function(err, teamData) {
        console.log("teams name  " + teamData);
    });
    

    或者,如果teamIds 是一串以逗号分隔的 id 值,则需要使用split 将其转换为值数组:

    Team.find({
        '_id': { $in: teamIds.split(',') }
    }, function(err, teamData) {
        console.log("teams name  " + teamData);
    });
    

    【讨论】:

    • _id 不在引号中工作吗? Team.find({ _id: { &in: teamIds } })
    • @Pete yes "_" 和 "$" 是合法的变量字符。
    猜你喜欢
    • 2019-04-29
    • 2017-12-05
    • 2016-01-01
    • 2015-05-26
    • 2018-04-04
    • 2020-09-15
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    相关资源
    最近更新 更多