17

I'm new to mongoose/mongodb

Say I'm saving something:

var instance = new TestingModel();
instance.test = 'blah2';
instance.save();

So when I save that the instance obj in the db will have, _id and test. But the _id attribute is added to the object only after entering the db. Note: I don't want to give it an id before. However, I want to grab the object in the db because I need to use the _id value, but I don't want to query it again. Is there a way where you save the object in the database and auto returns the database object so you can get the _id value?

Derek
  • 11,980
  • 26
  • 103
  • 162

3 Answers3

35

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...
Ricardo Tomasi
  • 34,573
  • 2
  • 55
  • 66
  • 1
    nice! just tested this. Hey where is the documentation on stuff like this? – Derek Sep 20 '11 at 04:52
  • and do u know of a way to do wat my question asked even tho ur answer does help me? just wondering... – Derek Sep 20 '11 at 04:53
  • 2
    I just looked at it again, and it seems the `_id` is generated when creating the object, so just grab it directly from `instance._id`. – Ricardo Tomasi Sep 20 '11 at 05:08
  • this does not quite answer the question , the question asked for returning the just saved object and not its id – Nelson Bwogora May 14 '21 at 05:27
  • @NelsonBwogora re-read the question. "and auto returns the database object so you can get the _id value" the poster needed to get the ID for a saved object. The saved object is already there, it's the `instance` var. – Ricardo Tomasi Jun 13 '22 at 15:08
1

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);
})
whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
Peter Huang
  • 972
  • 4
  • 12
  • 34
1
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 });
    });
});