繁体   English   中英

如何通过Mongoose中的对象数组找到?

[英]How to find by array of objects in Mongoose?

我有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!');
    }
  });
});

将该数组用作$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!');
    }
});

你可以试试

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM