我正在学习一些节点,并一直在尝试使用猫鼬.目前,我的目标是学习如何使用
populate.
我有项目定义和里程碑要求:
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的项目数据:
{ "title": "sitename","description": "online thing","creation_date": { "$date": "2013-07-11T19:45:42.139Z" },"_id": { "$oid": "51df0b66dbdd7c4f14000001" },"milestones": [],"milestone_ids": [],"__v": 0 }
这个是与项目基本相关的里程碑:
{ "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,due_date: Date,project_id: { type: String,ref: "Project" } }) Milestone = mongoose.model("Milestone",milestoneschema);
解决方法
您需要获得定义查询选项然后执行的顺序,并且可链接的API(例如mongoose Query)无法知道在查询触发后您可能调用的其他方法.因此,当您将回调传递给.find时,mongoose会立即发送查询.
通过回调查找
>查询定义的查询
>因为回调就在那里,查询立即执行并向DB发出命令
>然后.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命令