gpt4 book ai didi

javascript - 在 Mongoose 中,如何根据相关集合中的值查找记录?

转载 作者:行者123 更新时间:2023-11-30 11:00:19 29 4
gpt4 key购买 nike

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

然后我想执行以下形式的查询,而不需要执行两个查询:

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 有效或存在,就应该这样做。

关于javascript - 在 Mongoose 中,如何根据相关集合中的值查找记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58083219/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com