MMR
MMR

Reputation: 3009

res.json() is not a function...mongoose

I am not sure where i went wrong,when i run the code,it says error res.json(res) is not a function......

my 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);
  });
};

Upvotes: 0

Views: 3482

Answers (1)

sarincasm
sarincasm

Reputation: 517

Use a different variable name when you do topics.save() than res. In your code, you are overwriting the original res and thus do not have access to the response object.

So this is what your code would look like

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

Upvotes: 1

Related Questions