简体   繁体   English

猫鼬.populate()不填充

[英]Mongoose .populate() does not populate

I have two schema's Role and User . 我有两个模式的RoleUser When I do a Role.find() I want to populate the users with the users that have that specific role. 当我执行Role.find()我想用具有该特定角色的用户来填充users

let roleSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  ...,
  users: [{
    type: mongoose.Schema.ObjectId,
    ref: 'User'
  }]
}, {
  timestamps: true,
});

const Role = mongoose.model('Role', roleSchema);
let userSchema = new Schema({
  username: {
    type: String,
    required: true,
  },
  ...,
  role: {
    type: mongoose.Schema.ObjectId,
    ref: 'Role'
  },
}, {
    timestamps: true,
  }
);

const User = mongoose.model('User', userSchema);

When I get the Role with the following code: 当我使用以下代码获取Role时:

Role.findById(req.params.roleId)
  .populate('users')
  .then(role => {
    res.send(role);
  }).catch(err => {
    res.send(err)
});

It returns the following: 它返回以下内容:

{  
   "users": [  

   ],
   "_id":"5c78006df35ca926534ad865",
   "name":"Role",
   "createdAt":"2019-02-28T15:38:21.741Z",
   "updatedAt":"2019-02-28T15:38:21.741Z",
   "__v":0
}

User.find().populate('role') works just fine, but Role.find().populate('users') doesn't. User.find().populate('role')正常工作,但Role.find().populate('users')无效。

Am I doing something wrong or don't I need .populate() in this case? 在这种情况下,我是在做错什么还是不需要.populate()

Nevermind. 没关系。 I think I had to use aggregate().lookup() for that all along... since there weren't any ids in Role.users ... 我想我一直都必须使用aggregate().lookup() ...因为Role.users中没有任何ID ...

Role.aggregate()
  .lookup({
    from: 'users',
    localField: '_id',
    foreignField: 'role',
    as: 'users'
  }).then( role => {
    res.send(role);
  });

This gave me the response I wanted. 这给了我想要的答复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM