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

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 中。

谢谢。

grr*_*enn 6

有一种方法可以做到这一点 - 它称为 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)

  • @skyzaDev 请定义“私生子”。在我看来,无论您是否使用类型,拥有一个具有令人惊讶的属性(您永远不知道它包含什么)的对象都是一种极易出错的解决方案,永远不应该使用。 (2认同)

小智 2

该方法是正确的,您应该看到您的数据填充在产品字段中。确保您有正确的数据和型号