i learning node , have been trying use mongoose. currently, goal learn how use populate.
i have projects
definition , milestone
require:
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")();
then @ point in projects.js
:
project.find(query, {}, {sort: {_id: -1}}, function (error, results) { callback(results); } ).populate("milestones");
how populate milestones?
here project
data mongo:
{ "title": "sitename", "description": "online thing", "creation_date": { "$date": "2013-07-11t19:45:42.139z" }, "_id": { "$oid": "51df0b66dbdd7c4f14000001" }, "milestones": [], "milestone_ids": [], "__v": 0 }
and 1 milestone
connected project:
{ "title": "proof of concept", "description": "make work.", "due_date": { "$date": "2013-07-11t19:46:38.535z" }, "project_id": "51df0b66dbdd7c4f14000001", "_id": { "$oid": "51df0b9edbdd7c4f14000002" }, "__v": 0 }
also, milestone schema:
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);
you need order right of defining query options executing, , chainable apis such mongoose query can't know additional methods might call after query fires. when pass callback .find
, mongoose sends query right away.
pass callback find
- query defined arguments
find
- since callback there, query executes , issues command db
- then
.populate
happens, has no effect query has been sent mongo
here's need do:
project.find(query, {}, { sort: { _id: -1 } }).populate("milestones").exec(function (error, results) { callback(results); });
or little more readable:
project .find(query) .sort('-_id') .populate('milestones') .exec(function(error, results) { callback(results); });
omit callback , use .exec
- query passed
.find
creates query object parameters - additional chained calls
.sort
,.populate
etc further configure query .exec
tells mongoose done configuring query , mongoose issues db command
Comments
Post a Comment