【问题标题】:$in is not working in loopback$in 在环回中不起作用
【发布时间】:2016-09-02 21:41:03
【问题描述】:

我有一个字符串数组如下:

['57b69c9d4ae615ef0e312af6','57b69bf477b8e5cd0eb38c88'];

我将其转换为 ObjectId,如下所示:

var objectIds = [];
  for(var i=0; i<expenseIds.length; i++){
    var _id = new ObjectId(expenseIds[i]);
    objectIds.push(_id);
  }

objectIds:

[ 57b69c9d4ae615ef0e312af6, 57b69bf477b8e5cd0eb38c88 ]

现在我在 mongoDb 中使用$in 查询来获取所有详细信息,如下所示:

app.models.xxxxx.find({"_id" : {"$in" : objectIds}}, function(err, res){
    if(err){

    } else {
      console.log(res);
    }
  });

但它没有过滤。 xxxxxx 集合中的所有文档都在返回。请分享您的想法。提前致谢。

编辑: 当我在 mongo shell 中运行命令时:

db.xxx.find({ _id: { '$in': [ 57b69c9d4ae615ef0e312af6, 57b69bf477b8e5cd0eb38c88 ] }});

它抛出错误:

SyntaxError: identifier starts immediately after numeric literal @(shell):1:35

【问题讨论】:

  • 好吧,显示您的确切查询(被执行)和集合中的文档。也许过滤器确实选择了所有文档。
  • 在将字符串转换为ObjectId 时可能存在问题。您是否尝试过不使用 new 关键字进行转换?
  • 稍微跑题了:你也可以把.map()当成var objectIds = expensesIds.map(function(id) { return new ObjectId(id); });
  • 使用var findJSON = {"_id" : {"$in" : objectIds}}; console.log("%j", findJSON); 之类的问题进行故障排除,以确保您的搜索符合您的预期。
  • 明白。我建议您记录您的搜索条件,而不是您的结果。

标签: arrays node.js mongodb


【解决方案1】:

您需要为您的模型启用allowExtendedOperators

//model.json
...
"options": {
    "validateUpsert": true,
    "mongodb": {
      ...
      "allowExtendedOperators": true
    }
  },
...

更新

你的过滤器也有问题。

app.models.xxxxx.find({where: {"_id" : {"$in" : objectIds}}}, function(err, res){
    if(err){

    } else {
      console.log(res);
    }
  });

您还使用内置运算符:

app.models.xxxxx.find({where: {id : {inq : objectIds}}}, function(err, res){
        if(err){

        } else {
          console.log(res);
        }
      });

【讨论】:

  • 抛出错误TypeError: Argument must be a string
  • @Subburaj 和 TypeError 例外,您需要将 id 作为文本发送
【解决方案2】:

如果你正在使用 mongoose 那么试试这个

var objectIds = [];
for(var i=0; i<expenseIds.length; i++){
var _id =  mongoose.Types.ObjectId(expenseIds[i]);
objectIds.push(_id);
}

或者你可以使用 MongoDb 来做到这一点

var ObjectId = require('mongodb').ObjectID;
var objectIds = [];
for(var i=0; i<expenseIds.length; i++){
var _id =  ObjectId(expenseIds[i]);
objectIds.push(_id);
}

如果这能解决您的问题,请告诉我

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 2013-09-18
    • 2011-02-14
    • 1970-01-01
    相关资源
    最近更新 更多