如何在model2中使用model1引用,以便model1中的更改​​自动反映在model2中

时间:2016-09-12 14:22:16

标签: node.js mongoose mongoose-schema mongoose-populate

我有两个模型组模型和用户模型

用户模型:

var mongoose       =   require('mongoose');
var groupSchema    =   mongoose.Schema({
   members      :   [{
        id      :   {
           type : mongoose.Schema.Types.ObjectId,
           ref  : 'user'
        },
        firstName   :   String,
        lastName    :   String,
        profilePic :    String

    }]
});

module.exports     =    mongoose.model('group', groupSchema,'group');

小组模特:

{{1}}

因此,当用户上传新的个人资料照片时,该照片的网址已保存在用户模型中,但该用户的个人资料照片也应自动更改为群组成员数组。

1 个答案:

答案 0 :(得分:0)

您只需将架构更改为

即可
var groupSchema = mongoose.Schema({members : [{
    id      :   {
       type : mongoose.Schema.Types.ObjectId,
       ref  : 'user'
    },
    otherprop1:   String,
    otherprop2  :   String,

}]});

然后使用populate在find

中获取用户数据
group.find({}).populate({path:"user", select: "firstName lastName profilePic"})
相关问题