[英]How to find by array of objects in Mongoose?
I have Mongoose.Schema like this: 我有Mongoose.Schema这样:
const pixelSchema = mongoose.Schema({
x: String,
y: String,
color: String,
});
Also I have array of objects like this: 我也有这样的对象数组:
let pixels = [
{x: 0, 1: 0, color: 'blue'},
{x: 0, y: 1, color: 'blue'},
{x: 0, y: 2, color: 'blue'},
]
How can I check is one of this elements is already exist in database? 我该如何检查数据库中是否已存在此元素之一? My solution now looks like this, but I think it's very inefficient.
我的解决方案现在看起来像这样,但我认为这是非常低效的。
pixels.map(pixel => {
Pixel.find(pixel, (err, pixels) => {
if (pixels) {
console.log('Find!');
}
});
});
Use that array as part of the $or
query document. 将该数组用作
$or
查询文档的一部分。 The $or
operator lets you perform a logical OR operation on an array of two or more expressions and selects the documents that satisfy at least one of the expressions. $or
运算符允许您对两个或多个表达式的数组执行逻辑OR运算,并选择至少满足其中一个表达式的文档。
So your query in the end should just be: 所以你的查询到底应该只是:
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!');
}
});
You can try like 你可以试试
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.