nlr_p nlr_p - 1 month ago 11
Node.js Question

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

Answer

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