How to populate object having array of object in mongoose?

那年仲夏 提交于 2020-08-10 19:13:12

问题


I want to populate the adminId path to User Model.
Here is the code

adminInfo: {
    _id: false,
    adminId: [{
      type: Schema.Types.ObjectId,
      ref: 'User'
    }]
 }

Here is a part of user schema:

// user schema
const UserSchema = new mongoose.Schema({
  name: {
    firstName: {
      type: String,
      trim: true,
      required: true,
    },
    lastName: {
      type: String,
      trim: true
    }
  },
  email: {
    type: String,
    trim: true,
    required: true,
    unique: true,
    lowercase: true
  },
  phone: {
    type: String,
    trim: true,
    minlength: 10,
  },
  password: {
    type: String,
    trim: true,
    required: true,
    minlength: 6
  }
});

I have tried using .populate('adminInfo.adminId') but it's giving empty array [] whereas .populate('adminInfo') giving array of admins ids but not getting populated to User model


回答1:


i don't think there is any problem with .populate('adminInfo.adminId') method.

are you sure that ref field is in CamelCase .

If not, try to change ref field ->

adminInfo: {
  _id: false,
  adminId: [{
    type: Schema.Types.ObjectId,
    ref: 'user'
  }]
}


来源:https://stackoverflow.com/questions/62531177/how-to-populate-object-having-array-of-object-in-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!