0

我有一个Category模型,它的唯一属性是name.

还有一个SubCategory模型,它有一个包含模型名称namecategory字符串字段Category

Category模型name更改时,SubCategory指向该类别的每个都应更新其category字段以匹配新名称。

我目前正在通过获取SubCategories指向某个类别的所有内容、遍历它们并更新它的类别字段来直接在路由处理程序上实现这一点。

我想在模型中实现这个逻辑,它应该属于。

Category我在模型上创建了一个预中间件,

CategorySchema.pre('save', function(next) {
  console.log('Saving ' + this.name);
  next();
});

负责PUT请求的路由处理程序使用更新后的名称保存模型,如下所示:

...
parentCategory.name = requestedName;
parentCategory.validate(function(validationError) {          
  if (validationError) {
    return res.send(response.BAD_REQUEST); 
  }     
  parentCategory.save(function(saveError) {       
    if(saveError) {
      return res.send(response.SERVER_ERROR);        
    }
  });
});
...

但是我打印了名称,所以我无法迭代它的子类别,因为我只能访问新名称。

我不确定我应该如何将旧名称和新名称都传递给中间件以在那里做这些事情。

4

2 回答 2

2

我可以通过像这样查询 Category 模型来访问旧值:

CategorySchema.pre('save', function(next) {
    var that = this;
    var updateEachSubCategory = function(subcategory) {
    subcategory.category = that.name;
    subcategory.save(function(saveError) {
      if(saveError) {
        console.log(saveError);
        return 1;                    
      }
    });
  };
    var updateChildrenCategoryField = function(err, subCategoriesArray) {
        solange.asyncFor(subCategoriesArray, updateEachSubCategory);   
    };
    var findChildren = function(categorySearchError, categoryFound) {
        if(!categorySearchError) {
            mongoose.models["SubCategory"].find({ category: categoryFound.name }, updateChildrenCategoryField);
        }
    };
    mongoose.models["Category"].findOne({ _id: this._id }, findChildren);
    next();
});

由于这是一个保存中间件,新名称尚未保存,因此我们可以通过查询模型来访问它。

于 2013-02-04T22:36:05.650 回答
0

我的解决方案是在 post init 中间件中备份属性值

schema.post('init', function(model) {
  model.oldValues = JSON.parse(JSON.stringify(model));
}

比我们可以在任何其他中间件中访问这些属性,例如this.someAttr === this.oldValues.someAttr在属性修改之前。

我写了一个要点来检查它

这是它的输出:

    ------------------
    预初始化属性
    文档是新的,再次运行应用程序
    ------------------
    ------------------
    发布初始化属性
    { _id: 55a37cc88ff0f55e6ee9be2d,
      name: '测试 1 - 12:07:88',
      __v: 0,
      准备好:真}
    设置 this.oldValues
    ------------------
    ------------------
    预存属性
    { _id: 55a37cc88ff0f55e6ee9be2d,
      name: '测试 1 - 12:07:16',
      __v: 0,
      准备好:假}
    ------------------
    ------------------
    后期保存属性
    { _id: 55a37cc88ff0f55e6ee9be2d,
      name: '测试 1 - 12:07:16',
      __v: 0,
      准备好:假}
    旧属性 (model.oldValues)
    { _id: '55a37cc88ff0f55e6ee9be2d',
      name: '测试 1 - 12:07:88',
      __v: 0,
      准备好:真}
    ------------------
于 2015-07-13T09:47:47.720 回答