簡體   English   中英

如何通過Mongoose中的對象數組找到?

[英]How to find by array of objects in Mongoose?

我有Mongoose.Schema這樣:

const pixelSchema = mongoose.Schema({
  x: String,
  y: String,
  color: String,
});

我也有這樣的對象數組:

let pixels = [
  {x: 0, 1: 0, color: 'blue'},
  {x: 0, y: 1, color: 'blue'},
  {x: 0, y: 2, color: 'blue'},
]

我該如何檢查數據庫中是否已存在此元素之一? 我的解決方案現在看起來像這樣,但我認為這是非常低效的。

pixels.map(pixel => {
  Pixel.find(pixel, (err, pixels) => {
    if (pixels) {
      console.log('Find!');
    }
  });
});

將該數組用作$or查詢文檔的一部分。 $or運算符允許您對兩個或多個表達式的數組執行邏輯OR運算,並選擇至少滿足其中一個表達式的文檔。

所以你的查詢到底應該只是:

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

你可以試試

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM