簡體   English   中英

mongoose 填充不填充

[英]mongoose populate doesn't populate

我有一個用戶列表,每個用戶都有一個練習列表。 我想匯總要顯示的基本用戶信息和他們的練習。

我做了以下事情:

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}
]

使用以下聚合查詢來獲取用戶和鍛煉數據。

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

您將獲得每個用戶的鍛煉數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM