3

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

2 Answers 2

2

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!');
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

If I need check all elements, I just need to use $and right?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.