【问题标题】:How to find by array of objects in Mongoose?如何通过 Mongoose 中的对象数组查找?
【发布时间】:2016-07-12 11:08:14
【问题描述】:

我有这样的 Mongoose.Schema:

const pixelSchema = mongoose.Schema({
  x: String,
  y: String,
  color: String,
});

我也有这样的对象数组:

let pixels = [
  {x: 0, 1: 0, color: 'blue'},
  {x: 0, y: 1, color: 'blue'},
  {x: 0, y: 2, color: 'blue'},
]

如何检查其中一个元素是否已存在于数据库中? 我的解决方案现在看起来像这样,但我认为它非常低效。

pixels.map(pixel => {
  Pixel.find(pixel, (err, pixels) => {
    if (pixels) {
      console.log('Find!');
    }
  });
});

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    将该数组用作 $or 查询文档的一部分。 $or 运算符允许您对包含两个或多个表达式的数组执行逻辑 OR 运算,并选择至少满足其中一个表达式的文档。

    所以你最后的查询应该是:

    let pixels = [
      {x: 0, y: 0, color: 'blue'},
      {x: 0, y: 1, color: 'blue'},
      {x: 0, y: 2, color: 'blue'},
    ];
    
    let query = { "$or": pixels };
    
    Pixel.find(query, (err, pixels) => {
        if (pixels) {
            console.log('Find!');
        }
    });
    

    【讨论】:

    • 如果我需要检查所有元素,我只需要使用$and 对吗?
    【解决方案2】:

    你可以试试

    let pixels = [
      {x: 0, 1: 0, color: 'blue'},
      {x: 0, y: 1, color: 'blue'},
      {x: 0, y: 2, color: 'blue'}
    ]
    
    Pixel.find({ "$or": pixels}, function(error, pixel) {
        if(pixel) {
            console.log('Found pixel');
        }
    } );
    

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      • 2021-09-04
      • 2020-06-07
      • 1970-01-01
      相关资源
      最近更新 更多