【问题标题】:Mongoose .populate() does not populateMongoose .populate() 不填充
【发布时间】:2023-03-30 03:42:01
【问题描述】:

我有两个架构 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()

【问题讨论】:

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


    【解决方案1】:

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

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

    这给了我想要的回应。

    【讨论】:

      猜你喜欢
      • 2020-05-18
      • 2016-02-14
      • 2021-04-26
      • 2019-06-13
      • 1970-01-01
      • 2019-01-31
      • 2020-11-19
      • 2014-09-04
      • 2018-07-06
      相关资源
      最近更新 更多