我有一个项目集合,用于存储客户ID和包含该ID以及客户名称的客户集合。
我需要返回客户名称而不是项目API端点的ID,为此,我尝试在Mongoose中使用虚拟填充。
我具有以下架构/模型配置...
const customerSchema = new mongoose.Schema({
"custId": String,
"custName": String,
"addr1": String,
"addr2": String,
"city": String,
"county": String,
"postcode": String,
"phone": String,
"email": String
});
customerSchema.virtual('names', {
ref: 'customers',
localField: 'custId',
foreignField: 'custId'
});
const projectSchema = new mongoose.Schema({
"projId": String,
"projName": String,
"custId": String,
"custName": {
type: mongoose.Schema.Types.ObjectId,
ref: 'customers'
},
"projDesc": String,
"projAdd1": String,
"projAdd2": String,
"projCity": String,
"projCounty": String,
"projPostcode": String,
"projLat": String,
"projLng": String,
"projStartDate": String,
"projEndDate": String,
"projStatus": String,
"projContacts": [
String
]
});
const custModel = mongoose.model("customers", customerSchema);
const projectModel = mongoose.model("projects", projectSchema);
并在我的API端点代码中使用以下查询...
var result = await projectModel.find().populate('names').exec();
API端点返回数据,但不包含custName。
有人可以帮助吗?
谢谢!
注意到我已经将虚拟机提供给客户模型,因此进行了如下更改...
const projectSchema = new mongoose.Schema({
"projId": String,
"projName": String,
"custId": String,
"custName": {
type: mongoose.Schema.Types.ObjectId,
ref: 'customers'
},
"projDesc": String,
"projAdd1": String,
"projAdd2": String,
"projCity": String,
"projCounty": String,
"projPostcode": String,
"projLat": String,
"projLng": String,
"projStartDate": String,
"projEndDate": String,
"projStatus": String,
"projContacts": [
String
]
});
projectSchema.virtual('names', {
ref: 'customers',
localField: 'custId',
foreignField: 'custId'
});
const customerSchema = new mongoose.Schema({
"custId": String,
"custName": String,
"addr1": String,
"addr2": String,
"city": String,
"county": String,
"postcode": String,
"phone": String,
"email": String
});
const custModel = mongoose.model("customers", customerSchema);
const projectModel = mongoose.model("projects", projectSchema);
答案 0 :(得分:0)
默认情况下,不将Mongoose中的虚拟填充添加到输出中。添加了以下内容,它起作用了...
projectSchema.set('toObject', { virtuals: true });
projectSchema.set('toJSON', { virtuals: true });