猫鼬填充不填充

时间:2021-03-12 11:10:57

标签: node.js mongodb mongoose

我有一个用户列表,每个用户都有一个练习列表。我想汇总要显示的基本用户信息和他们的练习。

我做了以下事情:

const userSchema = new mongoose.Schema({
  name: {
  type: String,
   required: [true, 'Invalid username'],
   unique: [true, 'This user already exists'],
  },
  exercises: { 
  type: [mongoose.Schema.Types.ObjectId],
   ref: 'Exercise' 
  }
})
User = mongoose.model('User', userSchema);

const exerciseSchema = new mongoose.Schema({
  user: {type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
  description: {type:String, required: true},
  duration: {type:Number, required: true},
  date: {type:Date, required: true},
});

Exercise = mongoose.model('Exercise', exerciseSchema);

但是,聚合部分仅显示用户的信息,并带有空的练习数组:

 User.
  find().
  populate({
    path: 'exercises',
    model: 'Exercise'
    }).
  exec().
  then(docs => res.json(docs).status(200)).
  catch(err => res.json(err).status(500))
})

给出:

[{
"exercises":[],
"_id":"6047b61bc7a4f702f477085b",
"name":"John Smith",
"__v":0}
]

1 个答案:

答案 0 :(得分:0)

使用以下聚合查询获取用户和运动数据。

User.aggregate([{
 "$lookup":{
     "localField":"exercises",
     "foriegnField":"_id",
     "from":"Exercise",
     "as" :"userExercises"
  }
}])

您将获得每个用户的锻炼数据。