我试图像关系数据库一样使用猫鼬。我有一个任务架构,需要引用客户端,用户和注释架构。
我发现了很多示例,这些示例可以用一个模式填充另一个模式,但是当我需要填充多个模式时,没有一个示例。我尝试了以下链接: https://mongoosejs.com/docs/populate.html http://ronaldroe.com/populating-multiple-fields-and-levels-with-mongoose/
findAll: function (req, res) {
Task
.find(req.query)
.sort({ date: -1 })
// populate associated user
.populate("user", "_id firstName lastName")
// populate associated client
.populate("client", "_id name")
// all notes for the task and when they were created
.populate("note", "_id content created_at")
.then(dbModel => {
res.status(200).json({
tasks: dbModel.map(model => {
return {
_id: model._id,
user: model.user,
client: model.client,
assignDate: model.assignDate,
assignedStatus: model.assignedStatus,
completionStatus: model.completionStatus,
description: model.description,
note: model.note,
};
})
})
})
.catch(err => res.status(422).json(err));
}
当我对此数据进行GET请求时,我得到以下信息:
"tasks": [
{
"_id": "5d6980d8459a8b9f0e133d04",
"user": [
{
"_id": "5d6afd8a101f355244adfd9a",
"firstName": "Dexter",
"lastName": "Morgan"
}
],
"assignDate": "2018-12-09T00:00:00.000Z",
"assignedStatus": "true",
"completionStatus": "in-progress",
"description": "This client needs to be contacted for future sales"
}
]
我还希望获得客户端ID和名称以及与此任务相关的所有注释。
答案 0 :(得分:0)
尝试以下代码:
findAll: function (req, res) {
Task
.find(req.query)
.sort({ date: -1 })
// populate associated user
.populate({path : 'user' , select: '_id firstName lastName'})
// populate associated client
.populate({path : 'client' , select: '_id name'})
// all notes for the task and when they were created
.populate({path : 'note' , select : '_id content created_at'})
.then(dbModel => {
res.status(200).json({
tasks: dbModel.map(model => {
return {
_id: model._id,
user: model.user,
client: model.client,
assignDate: model.assignDate,
assignedStatus: model.assignedStatus,
completionStatus: model.completionStatus,
description: model.description,
note: model.note,
};
})
})
})
.catch(err => res.status(422).json(err));
}