如何在mongoose中嵌套填充?

时间:2015-07-28 11:43:34

标签: node.js mongodb mongoose

我的项目让我只允许school Admin为相应的学校插入学生的数据,我应该显示用他输入的学生详细信息插入数据的school Admin的详细信息。

我的students架构架构如下:

    userId: {
        type: Object,
        ref: 'User'
    },
    ugId:{
        type:Number

    },
    firstName:{
        type:String,
        required:true
    },
    lastName:{
       type:String,
       required:true    
    }

您可以在此处看到userId指的是名为User的模型,其模式如下:

    email: {
        type: String,
        required: true,
        index: true,
        unique: true
    },
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    userName: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    mappedUserDetails2: {
        type: Schema.Types.ObjectId,
        ref: 'Students'
    },
    UserGroupID: {
        type: Object,
        ref: 'UserGroups'
    }

在用户架构中,UserGroupID指的是UserGroups模型,其架构如下:

 groupName: {
        type: String,
        required: true,
        index: true,
        unique: true
    },
    createdDate: {
        type: Date,
        default: Date.now
    },
    updatedDate: {
        type: Date,
        default: Date.now
    },
    uid: {
        type: Number,
        min: 1
    },
    mappedUserDetails3: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    }

我发布的数据如下

{
  "userId":"55b7320173ceb5640e1b24a6",
  "ugId":3,
  "firstName":"AGGI",
  "lastName":"AGGIqa"
}

成功完成API后收到的输出如下

 { 
  "success": true,
  "userData":{
             "_id": "55b758a09472f03310cdb9a2",
             "userId":{
                 "_id": "55b7320173ceb5640e1b24a6",
                 "email": "XYZ@gmail.com",
                 "firstName": "XYZ",
                 "lastName": "XYZ",
                 "userName": "XYZ XYZ",
                 "UserGroupID": "55b7138c049d0d5d0dddd824",
                 "__v": 0
                },
              "firstName": "AGGI",
              "lastName": "AGGIqa",
              "ugId": 3,
              "__v": 0
}

My Question :我想知道有一种方法可以填充已填充的UserGroupID中的userId,因为UserGroupID是引用objectId模型的UserGroup

populate的{​​{1}}代码如下:

userId

1 个答案:

答案 0 :(得分:1)

默认情况下,Mongoose不提供此功能,但您可以write your own plugin,否则您可以使用mongoose-deep-populate,这正是您所需要的。