我正在使用 mongoose populate 尝试在我的模式中创建一对多关系
var clientSchema = new mongoose.Schema({
name: { type: String, required: true },
title: { type: String, default: "N/S" },
birthDate: { type: Date },
ssn: { type: String, default: "N/S" },
spouse: { type: String, default: "N/S" },
notes: { type: String, default: "N/S" },
address: { type: String, default: "N/S" },
city: { type: String, default: "N/S" },
state: { type: String, default: "N/S" },
zip: { type: String, default: "N/S" },
homePhone: { type: String, default: "N/S" },
workPhone: { type: String, default: "N/S" },
mobilePhone: { type: String, default: "N/S" },
fax: { type: String, default: "N/S" },
email: { type: String, default: "N/S" }
});
var caseSchema = mongoose.Schema({
_client: { type: mongoose.Schema.Types.ObjectId, ref: 'Client' },
name: { type: String, required: true },
lead: { type: String },
priority: { type: String },
dateOpened: { type: Date },
dateAccident: { type: Date },
status: { type: String },
sol: { type: Date },
description: { type: String }
});
我想要做的是查询数据库以获取具有给定 _client id 的所有案例。我有这个工作,但不是我想要的方式。截至目前,当我在我的路线中使用填充方法时,我得到了具有该客户端 ID 的所有案例,但我也得到了所有客户端,即使所有客户端都完全相同. 为每种情况返回相同的客户端似乎是一种资源浪费。有没有办法只返回一次客户,然后所有相关的案例都用它?
app.get('/cases/:id', function( req, res ) {
Case
.find( { _client: req.params.id } )
.populate('_client')
.exec( function( err, cases ) {
res.send( cases );
});
});
这是我要回来的:
[
{
"_client": {
"name": "John Doe",
"birthDate": null,
"_id": "51705a7ed0ecd0a906000001",
"__v": 0,
"email": "",
"fax": "",
"mobilePhone": "",
"workPhone": "",
"homePhone": "",
"zip": "",
"state": "",
"city": "",
"address": "",
"notes": "",
"spouse": "",
"ssn": "",
"title": "Mr"
},
"name": "test",
"lead": "",
"priority": "",
"dateOpened": null,
"dateAccident": null,
"status": "",
"sol": null,
"description": "",
"_id": "5170679df8ee8dd615000001",
"__v": 0
},
{
"_client": {
"name": "John Doe",
"birthDate": null,
"_id": "51705a7ed0ecd0a906000001",
"__v": 0,
"email": "",
"fax": "",
"mobilePhone": "",
"workPhone": "",
"homePhone": "",
"zip": "",
"state": "",
"city": "",
"address": "",
"notes": "",
"spouse": "",
"ssn": "",
"title": "Mr"
},
"name": "newest case",
"lead": "",
"priority": "",
"dateOpened": null,
"dateAccident": null,
"status": "",
"sol": null,
"description": "",
"_id": "517067d8806f060b16000001",
"__v": 0
},
{
"_client": {
"name": "John Doe",
"birthDate": null,
"_id": "51705a7ed0ecd0a906000001",
"__v": 0,
"email": "",
"fax": "",
"mobilePhone": "",
"workPhone": "",
"homePhone": "",
"zip": "",
"state": "",
"city": "",
"address": "",
"notes": "",
"spouse": "",
"ssn": "",
"title": "Mr"
},
"name": "adding new case",
"lead": "Me",
"priority": "Urgent",
"dateOpened": null,
"dateAccident": null,
"status": "",
"sol": null,
"description": "",
"_id": "51709a16806f060b16000002",
"__v": 0
}
]
将所有这些臃肿发送到我的视图进行渲染似乎并不正确。我什至应该像这样使用填充一对多吗?我在 mongoose.com 上看到的所有示例都是一对一的,嵌入式文档除外。