【问题标题】:How do I perform an id array query in Mongoose? [duplicate]如何在 Mongoose 中执行 id 数组查询? [复制]
【发布时间】:2011-08-14 16:02:33
【问题描述】:

假设我有一个名为User 的模型。 我有一个带有对象 ID 的数组。

我想获取与我拥有的 Id 数组“相交”的所有用户记录。

User.find({ records with IDS IN [3225, 623423, 6645345] }, function....

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    Ids 是对象 id 的数组:

    const ids =  [
        '4ed3ede8844f0f351100000c',
        '4ed3f117a844e0471100000d', 
        '4ed3f18132f50c491100000e',
    ];
    

    带回调:

    User.find().where('_id').in(ids).exec(callback);
    

    带异步功能:

    records = await User.find().where('_id').in(ids).exec();
    

    【讨论】:

      【解决方案2】:

      你需要使用 $in 操作符 >

      https://docs.mongodb.com/manual/reference/operator/query/in/#op._S_in

      例如:

      Users.find( { "fb" : { id: { $in : arrayOfIds } } }, callback );
      

      【讨论】:

      • 但是猫鼬的语法是什么?
      • 语法相同。 .find() 是一个 mongodb 函数。
      • 谢谢。如果我的“id”实际上是嵌套的怎么办。对象是: { fb: { name:blah, id:blah } } 。我将如何通过该 ID 查询它?你能帮我写出来吗?坦克。
      • Users.find( { "fb" : { id: { $in : arrayOfIds } } } );我没有测试过,但是应该可以的
      • “fb”是怎么回事?这对我不起作用,但确实如此:Users.find({_id: {$in:arrayOfIds} })
      【解决方案3】:

      对我来说,这样工作

      IDs=["5b00c4b56c7fb80918293dd9","5b00c4b56c7fb80918293dd7",...]
      const users= await User.find({records:IDs}) 
      

      【讨论】:

        【解决方案4】:

        这是使用 $in 运算符的一种猫鼬方式。

        User.find()
          .where('fb.id')
          .in([3225, 623423, 6645345])
          .exec(function (err, records) {
            //make magic happen
          });
        

        我发现点符号对于查询子文档非常方便。

        http://mongoosejs.com/docs/queries.html

        【讨论】:

        • 我想这应该是预期的答案,因为它以更清晰的语法提供了答案
        • 不知道我们可以在 mongoose 中链接命令!非常感谢
        【解决方案5】:
        User.where({ records: { $in: [3225, 623423, 6645345] } }, function ...
        

        更多信息在这里:http://docs.mongodb.org/manual/reference/operator/query/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-07-21
          • 2022-01-25
          • 1970-01-01
          • 1970-01-01
          • 2017-04-29
          • 1970-01-01
          • 2014-01-09
          • 1970-01-01
          相关资源
          最近更新 更多