Nat*_*hew 9 mongoose node.js express mongoose-populate
我正在与 mongoose 合作将 ids 字段与他们各自的文档填充到一个新字段中。我的问题是假设我的购物车模型是 -
let CartSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
productIds: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Product'
}
]
});
Run Code Online (Sandbox Code Playgroud)
我想填充产品所以我使用
Cart.find({}).populate("products").exec(function (err, cart) {
console.log(cart)
}
Run Code Online (Sandbox Code Playgroud)
但这会以相同的字段名称 productIds 填充文档,我想在名为“products”的新字段名称中填充这些字段,所以我尝试了这个
let CartSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
productIds: [
{
type: String
}
]
}, { toJSON: { virtuals: true } });
CartSchema.virtual('products', {
ref: 'Product',
localField: 'productIds',
foreignField: '_id',
});
Cart.find({}).populate("products").exec(function (err, cart) {
console.log(cart)
}
Run Code Online (Sandbox Code Playgroud)
但返回名为 products.so 的空数组,我如何将 productIds 数组填充到具有各自文档数组的新字段名称 products 中。
谢谢。
有一种方法可以做到这一点 - 它称为 Virtuals(请参阅文档)。这个想法是创建一个“虚拟属性”,它实际上并未保存到数据库中并充当计算属性。根据qinshenxue在相关github问题上提供的示例:
// declare your ID field as a regular string
var countrySchema = new mongoose.Schema({
capitalId: {type:String}
});
// create a virtual field which links between the field you've just declared
// and the related collection.
// localField is the name of the connecting field,
// foreign field is a corresponding field in the connected collection
// justOne says that it'll populate a single connected object,
// set it to false if you need to get an array
countrySchema.virtual('capital',{
ref: 'City',
localField: 'capitalId',
foreignField: '_id',
justOne: true
});
// tell Mongoose to retreive the virtual fields
countrySchema.set('toObject', { virtuals: true });
countrySchema.set('toJSON', { virtuals: true });
// now you can populate your virtual field like it actually exists
// the following will return a Country object in the 'capital' field
Country.find().populate('capital')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4391 次 |
最近记录: |