Mongoose with mongodb how to return just saved object?
The correct way to check is the callback of save :
instance.save(function(err,savedObj){
// some error occurs during save
if(err) throw err;
// for some reason no saved obj return
else if(!savedObj) throw new Error("no object found")
else console.log(savedObj);
})
The _id
should be present after saving:
var instance = new TestingModel()
instance.test = 'blah'
instance.save(function(err){
console.log(instance._id) // => 4e7819d26f29f407b0...
})
edit: actually the _id
is set on instantiation, so it should already be there before save:
var instance = new TestingModel()
console.log(instance._id) // => 4e7819d26f29f407b0...
router.post('/', function(req, res) {
var user = new User();
user.name = req.body.name;
user.token = req.body.token;
user.save(function(err, obj) {
if (err)
res.send(err);
res.json({ message: 'User created!', data: obj });
});
});