【问题标题】:Mongoose: issues populating an object in an arrayMongoose:在数组中填充对象的问题
【发布时间】:2016-04-23 05:25:47
【问题描述】:

我有以下三种型号:

var User = {
first_name: String,
last_name: String,
}

var Student = {
role = String,
user = {type: mongoose.Schema.Types.ObjectId, ref: 'User'}
groups = [{type: mongoose.Schema.Types.ObjectId, ref: 'Group'}],
}

var Group = {
name = String,
students = [{type: mongoose.Schema.Types.ObjectId, ref: 'Student'}],
}

我的快速获取方法如下:

router.route('/')
  .get(function(req, res){
    Group.find().populate('students').exec(function(err, groups){
      res.json(groups);
    });

我的 json 对象返回填充的学生对象数组,但我只从每个学生对象中接收一个 user._id。我怎样才能让用户对象填充?任何信息都会很棒!谢谢

【问题讨论】:

  • 为什么在 Student 和 Group 对象中的键和值用“=”而不是“:”分开?
  • 我的错误,只是一个错字。我在实际模型中使用了冒号:)

标签: javascript mongodb express mongoose mean-stack


【解决方案1】:

您可以跨多个级别填充:

router.route('/')
  .get(function(req, res){
    Group
      .find()
      .populate({
        path: 'students',
        // Get the student's user ids
        populate: { path: 'user' }
      })
      .exec(function(err, groups){
        res.json(groups);
      });

您可以阅读更多关于它的信息here

【讨论】:

  • 太棒了!谢谢你。它有效且易于理解!
  • 感谢您的资源!我之前阅读过 mongoose 文档,但忽略了有关跨多个级别填充的部分。
  • 很高兴能帮上忙。
猜你喜欢
  • 2022-01-24
  • 2016-01-19
  • 2017-10-26
  • 1970-01-01
  • 2019-09-23
  • 2011-06-10
  • 2019-07-28
  • 2020-06-01
  • 2020-11-11
相关资源
最近更新 更多