我一直在查看线程和 mongoose 文档,但仍然缺少有关包含子文档的内容。我有 REST api 与 express 一起运行,当您查找“人”时,我想从“位置”ID 中提供“位置”详细信息。下面是我的两个架构。
您会看到我正在尝试使用位置的标题填充 people.location .. 但最终我想包含架构中的所有详细信息。people.location 包含存在的位置的 id。
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' });
}
我带着这个从 /people 回来
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);
}
});
});
并且位置字段即将变为空,即使它在那里有 id。如果有人能给我任何指示或相关链接,那就太好了!如果您需要我发布其他内容,请告诉我。