我的裁剪模型有此架构
var CropSchema = new mongoose.Schema({
name: String,
zones: [{
type: Schema.Types.ObjectId,
ref: 'zone'
}],
...
});
我的区域模型的此架构
var ZoneSchema = new mongoose.Schema({
name: String,
poor: [{
type: Schema.Types.ObjectId,
ref: 'condition'
}],
...
});
此架构适用于我的条件模型
var ConditionSchema = new mongoose.Schema({
name: String,
action_on_controls: [{
type: Schema.Types.ObjectId,
ref: 'control'
}],
...
});
以及我的控件模型的此架构
var ControlSchema = new mongoose.Schema({
name: String,
...
});
我在节点中获取所有作物的方式是这样的:
public index(req: Request, res: Response) {
return Crop.find().populate('zones').populate({
path: 'zones',
populate: [
{
path: 'poor', populate: [
{ path: 'action_on_controls' }]
}
]
}).exec()
.then(respondWithResult(res, 200))
.catch(handleError(res, 500));
}
我获得个人作物的方式是这样的:
public show(req: Request, res: Response) {
return Crop.findById(req.params.id).populate({
path: 'zones',
populate: [
{
path: 'poor', populate: [
{ path: 'action_on_controls' }]
}
]
}).exec()
.then(handleEntityNotFound(res))
.then(respondWithResult(res, 200))
.catch(handleError(res, 500));
}
如您所见,部分:
.populate({..}(
重复两次。
如何保持相同的填充配置,这样我就不必一直编写/更新相同的内容?
您可以将填充对象另存为变量并共享:
const zonePopulateObj = {
path: 'zones',
populate: [
{
path: 'poor', populate: [
{ path: 'action_on_controls' }]
}
]
};
然后在您的查询中
return Crop.find().populate(zonePopulateObj).exec();
return Crop.findById(req.params.id).populate(zonePopulateObj).exec();
或者,您可以将查询逻辑拉入新函数并共享该函数
public index(req: Request, res: Response) {
return findCrop()
.then(respondWithResult(res, 200))
.catch(handleError(res, 500));
}
public show(req: Request, res: Response) {
return findCrop(req.params.id)
.then((array)=>array.length ? array[0] : {})
.then(handleEntityNotFound(res)) // may need to update this function not sure how it checks for not found.
.then(respondWithResult(res, 200))
.catch(handleError(res, 500));
}
const findCrop = (id)=>{
let queryObj = {};
if(id){
queryObj._id=id
}
return Crop.find(queryObj).populate({
path: 'zones',
populate: [
{
path: 'poor', populate: [
{ path: 'action_on_controls' }]
}
]
}).exec()
}
就个人而言,我更喜欢第一种方法。