And*_*e M 2 javascript mongoose mongodb node.js typescript
在 Mongoose 中,我有两个集合,一个引用另一个。是否可以有一个查找查询,根据另一个中的值选择记录。我试图得到的一个例子(不是实际的模式):
const CarModelSchema = new mongoose.Schema({
name: String,
brand: { type: mongoose.Schema.Types.ObjectId, ref: 'CarBrand' }
});
const CarBrandSchema = new mongoose.Schema({
name: String,
country: String
});
Run Code Online (Sandbox Code Playgroud)
然后我想执行表单的查询,而无需执行两个查询:
CarModelSchema.find({ 'brand.country': 'GER' });
Run Code Online (Sandbox Code Playgroud)
到目前为止,我还没有能够完成这项工作,所以我想知道这是否可以在 Mongo 中完成,或者我是否走错了路?
对的,这是可能的。
我意识到你的模式没有模型,所以像这样添加它们:
const CarModel = mongoose.model('CarModel', CarModelSchema);
const CarBrand = mongoose.model('CarBrand', CarBrandSchema);
Run Code Online (Sandbox Code Playgroud)
品牌也应该这样定义:
brand: [{ type: mongoose.Schema.Types.ObjectId, ref: 'CarBrand' }] //added the brackets
Run Code Online (Sandbox Code Playgroud)
然后,您可以通过执行以下操作运行查找查询以按国家/地区过滤:
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();
Run Code Online (Sandbox Code Playgroud)
只要保存在集合中brands
数组中的ObjectIdsCarModel
有效或存在,就应该这样做。