How to use mongoose filling?

I am learning some node and trying to use mongoose. My current goal is to learn how to use populate .

I have some projects and milestone required:

 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 I do this at some point in projects.js :

 Project.find(query, {}, {sort: {_id: -1}}, function (error, results) { callback(results); } ).populate("milestones"); 

How to fill in control points?


Here are the project data from mongo:

 { "title": "sitename", "description": "online thing", "creation_date": { "$date": "2013-07-11T19:45:42.139Z" }, "_id": { "$oid": "51df0b66dbdd7c4f14000001" }, "milestones": [], "milestone_ids": [], "__v": 0 } 

And this is one milestone , which is mainly related to the project:

 { "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 } 

In addition, this is a reference circuit:

 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); 
+6
source share
1 answer

You need to have the right to determine the query parameters and then execute, and the connected APIs, such as mongoose Query, cannot know what additional methods you could call AFTER the query. So when you pass the callback to .find , mongoose sends the request right away.

Pass find callback

  • defined by find arguments
  • since the callback exists, the query is immediately executed and issues a DB command
  • then .populate happens, but this has no effect as the request has already been sent to mongo

Here is what you need to do:

 Project.find(query, {}, { sort: { _id: -1 } }).populate("milestones").exec(function (error, results) { callback(results); }); 

Or read a little:

 Project .find(query) .sort('-_id') .populate('milestones') .exec(function(error, results) { callback(results); }); 

Cancel callback and use .exec

  • request transmitted in .find , generates query object with parameters
  • additional chain calls .sort , .populate , etc. further configure the request
  • .exec tells mongoose that you have finished setting up the query and mongoose problems with the DB command
+11
source

Source: https://habr.com/ru/post/949241/


All Articles