我正在与 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)