猫鼬|对所有功能保持相同的人口

时间:2019-06-13 13:25:45

标签: node.js angular mongoose mean-stack mongoose-populate

  

我的作物模型具有这种模式

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,
    ...
});
  

我在Node中获取所有农作物的方法是:

  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({..})

重复两次。

如何保持相同的填充配置,这样我就不必一直写/更新相同的东西?

1 个答案:

答案 0 :(得分:1)

您可以将填充对象另存为变量并共享:

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()
  }

我个人更喜欢第一种方法。