我的方案是从模型1(employee.js)查询 getEmp_onId ,这将从模型2(empdetails.js)填充员工详细信息< /强>
问题:
当我在模型1(employee.js)上运行查询时,我获得员工数据,但其中没有填充数据
[
{"_id": "552790d18d3a9810ee5c26c0",
"username": "demo person"
"email": "test@example.com"
}
]
但令人震惊的是,当我直接在模型2(empdetails.js)上运行查询时,我从模型1(employee.js)获取填充数据!!
[
{"_id": "552ca14069303a15eda1bc95",
"emp_id": {
"_id": "552790d18d3a9810ee5c26c0",
"username": "demo person"
"email": "test@example.com"
},
"city": "demo city",
"state": "demo state",
"country": "demo country"
}
]
任何人都可以解释一下mongoose模型是如何填充作品的吗?
型号:1
employee.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema;
var collection_name = 'employees';
var employee_schema = new Schema({
_id: {type: Schema.ObjectId}, username: {type: String}, email: {type: String, unique: true},
emp_details: {type: Schema.Types.ObjectId, ref: 'empdetails'}
});
employee_schema.methods = {
getEmp_onId: function(empid, cb) {
this.model(collection_name)
.find({ _id: empid })
.populate('emp_details')
.exec(function(err, res) {
if(err) { cb(err, null); }
else { cb(null, res); }
});
}
};
型号:2
empdetails.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema;
var collection_name = 'empdetails';
var schema = new Schema({
_id: {type: Schema.ObjectId},
emp_id: {type: Schema.Types.ObjectId, ref: 'employees'},
city: {type: String}, state: {type: String}, country: {type: String}
});
schema.methods = {
emp_details_by_id: function(empid, cb) {
this.model(collection_name)
.find({ emp_id: empid })
.populate('emp_id')
.exec(function(err, res) {
if(err) { cb(err, null); }
else { cb(null, res); }
});
}
};
答案 0 :(得分:0)
我猜你是先保存员工,然后再用员工ID保存详细信息。这意味着,您的详细信息文档引用了员工文档,但员工文档没有参考。你应该这样做:
employee = new employee_model({username: 'username', email: 'email'});
details = new detail_model({emp_id: employee.id, city: 'City'});
employee.emp_details = details.id;
employee.save();
details.save();