📅  最后修改于: 2023-12-03 15:01:20.756000             🧑  作者: Mango
在使用Mongoose进行嵌套查询时,如何按其引用模型的字段来对模型进行查询?
可以使用Mongoose的populate()方法进行嵌套查询。具体步骤如下:
在模型中设置字段引用。
const ProductSchema = new mongoose.Schema({
name: String,
price: Number,
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Category'
}
});
使用populate()方法。
Product.find()
.populate({ path: 'category', match: { name: 'Electronics' } })
.exec((err, products) => {
console.log(products);
});
在path中传递字段引用的名称(即在模型中设置的name),在match中设置查询条件即可。
const mongoose = require('mongoose');
const CategorySchema = new mongoose.Schema({
name: String
});
const ProductSchema = new mongoose.Schema({
name: String,
price: Number,
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Category'
}
});
const Category = mongoose.model('Category', CategorySchema);
const Product = mongoose.model('Product', ProductSchema);
mongoose.connect('mongodb://localhost/nested_query');
const ipad = new Product({
name: 'iPad Air',
price: 799,
category: new Category({ name: 'Electronics' })
});
ipad.save((err, savedProduct) => {
Product.find()
.populate({ path: 'category', match: { name: 'Electronics' } })
.exec((err, products) => {
console.log(products);
mongoose.disconnect();
});
});