I have Mongoose.Schema like this:
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. 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.
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');
}
} );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.