semanser semanser - 4 months ago 30
Node.js Question

How to find by array of objects in Mongoose?

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

Answer

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