小编Nat*_*hew的帖子

将 Mongoose 对象从 id 填充到新字段

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

mongoose node.js express mongoose-populate

9
推荐指数
2
解决办法
4391
查看次数

标签 统计

express ×1

mongoose ×1

mongoose-populate ×1

node.js ×1