在特定情况下删除我的json字段

时间:2016-01-20 10:43:43

标签: javascript node.js express

我有一个列出所有用户的ExpressJS控制器

userCtrl.get

get(req, res, next) {
  var func = function(err, data) {
    if (err) return next(err);
    return res.json(data);
  };

  if (req.params[this.idName])
    this._getById(req.params[this.idName], func);
  else
    this._getAll(func);
  }

  _getById(id, fn) {
    this.ObjectClass.findById(id, fn);
  }
  _getAll(fn) {
    this.ObjectClass.findAll(fn);
  }

我想从另一条道路上调用它,以这种方式 res.json()将过滤此json的字段 类似的东西:

router.get ('/services/:serviceKey/authBridge/users', function(req, res, next) {
  function anonJs(x) {
    x.forEach(s => s.credential = null);
    res.json(x);
  }
  res.json = anonJs;
  userCtrl.get(req, res, next);
});

问题是,在最后一段代码中,当我调用res.json时,我最终会收到一个递归,现在定义为anonJS

1 个答案:

答案 0 :(得分:0)

在更换之前,您必须存储对旧功能的引用。

router.get ('/services/:serviceKey/authBridge/users', function(req, res, next) {
  var json = res.json;
  res.json = function(x) {
    x.forEach(s => s.credential = null);
    json(x);
  }

  userCtrl.get(req, res, next);
});