猫鼬:我们可以将引用对象填充到别名/虚拟属性吗?

pha*_*ong 5 mongoose mongoose-populate mongoose-schema

我正在寻找一种使用猫鼬填充到别名/虚拟属性的方法?

就目前而言,猫鼬的种群是在引用属性中添加更多字段(通常是身份密钥)。我想保留原始属性,然后将引用的数据填充到其他属性。

例如:似乎我们需要更多的架构选项

profile_id: { type: mongoose.Schema.Types.ObjectId, ref: 'profiles', populateTo: 'profile' }
Run Code Online (Sandbox Code Playgroud)

结果返回应包含两个属性:profile_idprofile

经过搜索之后,我在github上发现了这个问题:( https://github.com/Automattic/mongoose/issues/3225

Alp*_*til 3

是的。您可以使用虚拟属性来填充引用对象。您需要做的就是在架构上定义一个虚拟属性,如下所示:

UserSchema.virtual('profile', {   
    ref: 'Profiles', // the collection/model name
    localField: 'profile_id',
    foreignField: '_id',
    justOne: true, // default is false
});
Run Code Online (Sandbox Code Playgroud)

然后使用填充方法:

User.find({}).populate({ path: 'profile', select: 'name status' })
Run Code Online (Sandbox Code Playgroud)

这将返回以下结果:

{   // USER
    _id: 'xx...1',
    username: 'alpesh',
    profile_id: 'xx......7',
    profile: {    // POPULATED
        name: 'Admin',
        status: 'Active
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意 - 如果您使用的是 nodejs/express:在定义架构时使用{ toJSON: { virtuals: true } }

请参阅 - https://mongoosejs.com/docs/populate.html