我正在学习一些节点,并一直在尝试使用猫鼬。目前,我的目标是学习如何使用populate。
我有一个projects
定义,milestone
需要:
projectSchema = new mongoose.Schema({
id: String,
title: String,
description: String,
owner: String,
site: String,
creation_date: Date,
milestone_ids: Array,
milestones: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Milestone"
}]
})
Project = mongoose.model("Project", projectSchema)
milestones = require(__dirname + "/milestones.js")();
然后我在projects.js
:
Project.find(query, {}, {sort: {_id: -1}},
function (error, results) {
callback(results);
}
).populate("milestones");
如何填充里程碑?
以下是来自mongo的project
数据:
{
"title": "sitename",
"description": "online thing",
"creation_date": {
"$date": "2013-07-11T19:45:42.139Z"
},
"_id": {
"$oid": "51df0b66dbdd7c4f14000001"
},
"milestones": [],
"milestone_ids": [],
"__v": 0
}
这一个是milestone
,基本上与项目有关:
{
"title": "Proof of concept",
"description": "Make it work.",
"due_date": {
"$date": "2013-07-11T19:46:38.535Z"
},
"project_id": "51df0b66dbdd7c4f14000001",
"_id": {
"$oid": "51df0b9edbdd7c4f14000002"
},
"__v": 0
}
此外,这是里程碑架构:
milestoneschema = new mongoose.Schema({
id: String,
title: String,
description: String,
owner: String,
site: String,
due_date: Date,
project_id: {
type: String,
ref: "Project"
}
})
Milestone = mongoose.model("Milestone", milestoneschema);
答案 0 :(得分:13)
您需要获得定义查询选项然后执行的顺序,并且可链接的API(例如mongoose Query)无法知道在查询触发后您可能调用的其他方法。因此,当您将回调传递给.find
时,mongoose会立即发送查询。
find
find
.populate
,但由于查询已经发送到mongo,因此无法生效以下是您需要做的事情:
Project.find(query, {}, {
sort: {
_id: -1
}
}).populate("milestones").exec(function (error, results) {
callback(results);
});
或者更具可读性:
Project
.find(query)
.sort('-_id')
.populate('milestones')
.exec(function(error, results) {
callback(results);
});
.exec
.find
的.sort
,.populate
等的其他链式调用进一步配置查询.exec
告诉mongoose你完成了配置查询并且mongoose发出了DB命令