res.json()不是函数... mongoose

时间:2016-10-15 10:27:57

标签: node.js mongoose

我不确定我哪里出错,当我运行代码时,它说错误res.json(res)不是函数......

我的node.js,

 exports.inserttopic = function (req, res) {
  var topics = new Topics(req.body);console.log(topics)
  topics.status = '1';
  topics.type = 'topics';
  var data = {};
  topics.save(function (err, res) {
    if (err) {
      console.log(err);
      return err;
    }
    data = { status: false, error_code: 1, message: 'Unable to insert' };
    if (res) {
      data = { status: true, error_code: 0, result: res, message: 'Inserted successfully' };
    }
    res.json(data);
  });
};

1 个答案:

答案 0 :(得分:1)

执行topics.save()而不是res时,请使用其他变量名称。在您的代码中,您将覆盖原始res,因此无权访问响应对象。

这就是你的代码看起来像

exports.inserttopic = function (req, res) {
  var topics = new Topics(req.body);console.log(topics)
  topics.status = '1';
  topics.type = 'topics';
  var data = {};
  topics.save(function (err, mongooseResponse) { \\ Do not use res here
    if (err) {
      console.log(err);
      return err;
    }
    data = { status: false, error_code: 1, message: 'Unable to insert' };
    if (mongooseResponse) {
      data = { status: true, error_code: 0, result: mongooseResponse, message: 'Inserted successfully' };
    }
    res.json(data);
  });
};