【发布时间】:2019-06-23 01:12:29
【问题描述】:
我正在使用 mongoose 将 id 字段及其各自的文档填充到一个新字段中。我的问题是假设我的购物车模型是 -
let CartSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
productIds: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Product'
}
]
});
我想填充产品,所以我使用了
Cart.find({}).populate("products").exec(function (err, cart) {
console.log(cart)
}
但这会将文档填充到相同的字段名称 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)
}
但返回了名为 products.so 的空数组,那么我如何将 productIds 数组填充到具有各自文档数组的新字段名称 products 中。
谢谢。
【问题讨论】:
标签: node.js express mongoose mongoose-populate