Last active
January 16, 2019 18:41
-
-
Save sriharshaj/e8d50a5b2777aaa6f892 to your computer and use it in GitHub Desktop.
Populate Plain JSON Objects in Mongoose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Company Schema | |
{ | |
name : String , | |
founded:Number, | |
headquaters : {"type":ObjectId, ref:"City"} | |
} | |
City Schema | |
{ | |
city_name:String, | |
pin :String | |
} | |
Employee Schema | |
{ | |
name : String, | |
age : Number, | |
company:{"type":ObjectId , ref: "Company"}, | |
residence:{"type":ObjectId , ref: "City"} | |
} | |
This document shows how to populate JSON object which has Employee data | |
*/ | |
//doc can be array of documents or single document | |
var doc =[ | |
{ | |
name:'harsha', | |
age :21, | |
company:'55815115a78e9d7346df81f2', | |
residence:'556be5c130a07d9c15337e2d' | |
}, | |
{ | |
name:'sri', | |
age :21, | |
company:'559f76303c89d6023677b295', | |
residence:'556be5c130a07d9c15337e33' | |
} | |
]; | |
//opts path: id's reference name , model : reference model , select: desire fields if empty it will return all fields . | |
// http://mongoosejs.com/docs/api.html#model_Model.populate -----> more opts | |
var opts =[ | |
{ | |
path:company , model:'Company' , select:'name' | |
}, | |
{ | |
path:residence , model:'City' , select:'city_name' | |
} | |
]; | |
Employee.populate(doc,opts,function(err,data){ | |
if(err){ | |
console.log(err); | |
return ; | |
} | |
console.log(data); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment