populate mongoose subdocuments with REST api
I've been looking over threads and the mongoose docs but am still missing
something about including subdocuments. I have REST api running with
express and i want to give the "location" details from the "location" id
when you lookup "people". Below are my two schema's.
You'll see i'm trying to populate people.location with the title of the
location.. but eventually i'd like to include all details from the schema.
people.location contains the id of a location that exists.
peopleSchema.js
module.exports = function(db) {
return db.model('People', PeopleSchema());
}
function PeopleSchema () {
var Schema = require('mongoose').Schema;
LocationsSchema = new Schema({
title: String
});
console.log(LocationsSchema);
return new Schema({
first_name: String,
last_name: String,
address: {
unit: Number,
address: String,
zipcode: String,
city: String,
region: String,
country: String
},
image: String,
job_title: String,
created_at: { type: Date, default: Date.now },
active_until: { type: Date, default: null },
hourly_wage: Number,
location: [{type: Schema.ObjectId , ref: 'Locations'}], // Inheirit
store info
employee_number: Number
}, { collection: 'people' });
}
locationSchema.js
module.exports = function(db) {
return db.model('Locations', LocationsSchema());
}
function LocationsSchema () {
var Schema = require('mongoose').Schema;
return new Schema({
title: String,
address: {
unit: Number,
address: String,
zipcode: String,
city: String,
region: String,
country: String
},
current_manager: String, // Inherit person details
alternate_contact: String, // Inherit person details
hours: {
sunday: String,
monday: String,
tuesday: String,
wednesday: String,
thursday: String,
friday: String,
saturday: String,
holidays: String
},
employees: "", // mixin employees that work at this location
created_at: { type: Date, default: Date.now },
active_until: { type: Date, default: null }
}, { collection: 'locations' });
}
and i'm returning from /people with this
app.get('/people', function (req, res) {
return PeopleModel.find().populate('location').exec(function (err, obj) {
if (!err) {
return res.send(obj);
} else {
return res.send(err);
}
});
});
and the location field is coming up null, even though it has the id in
there. If anybody could give me any pointers or related links that would
be great! Let me know if you need me to post anything else.
No comments:
Post a Comment