semanser
semanser

Reputation: 2348

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

Upvotes: 3

Views: 441

Answers (2)

Shaishab Roy
Shaishab Roy

Reputation: 16805

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

Upvotes: 0

chridam
chridam

Reputation: 103365

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

Upvotes: 2

Related Questions