如何查找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'}, ] 

我怎样才能检查这个元素之一是否已经存在于数据库中? 我的解决scheme现在看起来像这样,但我认为这是非常低效的。

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

使用该数组作为$or查询文档的一部分。 $or操作符允许您对两个或多个expression式的数组执行逻辑或操作,并select至less满足一个expression式的文档。

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

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