簡體   English   中英

在mongoose中,如何根據相關集合中的值查找記錄?

[英]In mongoose, how to find records based on value in related collection?

在 Mongoose 中,我有兩個 collections,一個引用另一個。 是否有可能有一個查找查詢,它根據另一個值選擇記錄。 我試圖得到的一個例子(不是實際的模式):

const CarModelSchema = new mongoose.Schema({
   name: String,
   brand: { type: mongoose.Schema.Types.ObjectId, ref: 'CarBrand' }
});

const CarBrandSchema = new mongoose.Schema({
   name: String,
   country: String
});

然后我想執行表單的查詢,而不需要執行兩個查詢:

CarModelSchema.find({ 'brand.country': 'GER' });

到目前為止,我還無法完成這項工作,所以我想知道這是否可以在 Mongo 中完成,或者我是否處理錯了?

對的,這是可能的。

我意識到您的模式沒有模型,所以像這樣添加它們:

const CarModel = mongoose.model('CarModel', CarModelSchema);
const CarBrand = mongoose.model('CarBrand', CarBrandSchema);

品牌也應該這樣定義:

brand: [{ type: mongoose.Schema.Types.ObjectId, ref: 'CarBrand' }] //added the brackets

然后,您可以通過執行以下操作運行查找查詢以按國家/地區過濾:

CarModel.
  find(...).
  populate({
    path: 'brand',
    match: { country: { $eq: 'GER' }},
    // You can even select the field you want using select like below, 
    select: 'name -_id',
    //Even limit the amount of documents returned in the array
    options: { limit: 5 }
  }).
  exec();

只要保存在CarModel集合中brands數組中的 ObjectId 有效或存在,就應該這樣做。

在您的人口中使用match將完成這項工作。

CarModel.find()
  .populate({
     path: 'brand',
     model: CarBrandModel,
     match: { country: { $eq: 'GER' }},
  })
  .exec()

請記住,您必須像這樣定義CarModelCarBrandModel

const CarModel = mongoose.model('CarModel', CarModelSchema)
const CarBrandModel = mongoose.model('CarBrandModel', CarBrandSchema)

是的,你做錯了。

CarModelSchema.brand中沒有保存字符串,保存了 ObjectId,因此您必須找到該 ObjectId(參考)。

您可以手動進行 - 首先找到CarBrandSchema.find({ 'country': 'GER' }); 然后使用其 ObjectId (= _id ),或者您可以使用https://mongoosejs.com/docs/populate.html使用 CarBrand ZA8CFDE6331BD4B62AC96F8911 填充您的 CarModel

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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