Daniel Rios Daniel Rios - 1 month ago 8
Node.js Question

Mongoose Model#save return value

I would like to get the whole document instead of the added item when I do a save().

var newTodo = Todos({
ID: req.body.ID,
RuleName: req.body.RuleName
});

newTodo.save(function (err, todos) {
if (err) throw err;
res.send(todos);
});

Answer

You cannot get it, unless you extend model method, or get it inside save

Simple version

newTodo.save(function (err, todos) {
     if (err) throw err;
     Todos.find(err, todos) {
         if (err) throw err;
         res.send(todos);
     }
});

Version with custom method

// in schema definition
TodosSchema.methods.saveAndFind = function(cb) {
  var self = this;
  self.save(function(err) {
    if(err) throw err;
    return self.model('Todos').find({}, cb);
  })
};
// in controller
var newTodo = Todos({
     ID: req.body.ID,
     RuleName: req.body.RuleName
});
newTodo.saveAndFind(function (err, todos) {
     if (err) throw err;
     res.send(todos);
});
Comments