猫鼬.populate()不填充

时间:2019-02-28 16:03:01

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

我有两个架构的RoleUser。当我执行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);

当我收到带有以下代码的Role时:

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

它返回以下内容:

{  
   "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')正常,但是Role.find().populate('users')无效。

在这种情况下我是做错了事还是不需要.populate()

1 个答案:

答案 0 :(得分:0)

没关系。我想我必须一直使用aggregate().lookup()……因为Role.users中没有任何ID ...

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

这给了我想要的答复。