How to get the ObjectID of a document just save()'ed?

420 views
Skip to first unread message

mkoistinen

unread,
Feb 19, 2011, 4:38:38 AM2/19/11
to mongoo...@googlegroups.com
Greetings all,

Apologies if this is a double post, I could have sworn I posted this two days ago, but it seems to have disappeared.

I'd like to get the ObjectID of the document I've just save()'ed.  It seems like this should be obvious, but I'm missing it.  Here's what I'm doing at the moment:

var Obj = db.model('Object');
app.post('/object', function(req, res) {

  doc = new Obj({ blah, blah });
  doc.save(function(err) {
    ...
    res.redirect('/object/' + doc._id);   <-- Hmmm, I don't actually have the _id... =(
  });
});

I've tried using a 'standard' callback on the save method with a signature like:

var Obj = db.model('Object');
app.post('/object', function(req, res) {

  tmp = new Obj({ blah, blah });
  tmp.save(function(err, obj) {
    ...
    res.redirect('/object/' + doc._id);   <-- Hmmm, I don't actually have the _id... =(
  });
});

but it doesn't seem to work.  What am I missing?

I'm using: Node v0.4.0, Mongoose v1.0.16, MongoDB v1.6.6-pre

mkoistinen

unread,
Feb 19, 2011, 5:03:23 AM2/19/11
to mongoo...@googlegroups.com
Sorry, that should be function(err, doc) in the second code block. Question still stands though.

Wyverald

unread,
Feb 20, 2011, 5:45:12 AM2/20/11
to mongoo...@googlegroups.com
var Obj = db.model('Object');
app.post('/object', function(req, res) {

  doc = new Obj({ blah, blah });
  doc.save(function(err) {
    ...
    res.redirect('/object/' + doc._id);   <-- Hmmm, I don't actually have the _id... =(
  });
});
The "doc" reference in the save callback should be the same as the one in the post callback, unless you defined another variable named "doc" in the save callback, in which case the inner variable overrides the outer.

The second code block (considering obj -> doc) wouldn't work, since the second parameter is not passed and is thus "undefined".

You can try "console.log(require('util').inspect(doc));" before the res.redirect to see what "doc" really points to.

mkoistinen

unread,
Feb 20, 2011, 7:55:27 AM2/20/11
to mongoo...@googlegroups.com
Here is my exact code I'm using with the exact console output:

app.post('/products', requiresLogin, function(req, res) {
  product = new Products(req.body.product);
  product.save(function(err) {
    if (err) {
      console.log(err);
      // Some form of error, do-over.
      res.redirect('/products/new');
    }
    else {
      console.log(require('util').inspect(product));
      // Now show the newly created product
      res.redirect('/products/' + product._id);   // <-- sadly, product._id is undefined
    }
  });
});

And here's the console output:

{ doc: 
   { name: 'Test Product',
     description: 'test product, delete me',
     price: { _atomics: [], _path: 'price', _parent: [Circular] },
  activePaths: 
   { paths: 
      { name: 'modify',
        description: 'modify',
        price: 'modify',
        photo: 'modify' },
     states: { init: {}, modify: [Object], require: {} },
     stateNames: [ 'require', 'modify', 'init' ],
     map: [Function],
     forEach: [Function] },
  saveError: null,
  pres: { save: { serial: [Object], parallel: [] } },
  isNew: false }

Notice that there is no _id field anywhere to be found.

Also notice that the object, product in this case is the same object throughout.

Also note that the save() works, my new product appears just fine in my database.

Does this work for you?

mkoistinen

unread,
Feb 21, 2011, 3:08:51 PM2/21/11
to mongoo...@googlegroups.com
Can someone confirm that it is, or is not possible please?

Guillermo Rauch

unread,
Feb 21, 2011, 3:44:01 PM2/21/11
to mongoo...@googlegroups.com
It's probably your use of a global `doc` instead of `var doc`


On Mon, Feb 21, 2011 at 12:08 PM, mkoistinen <mkois...@gmail.com> wrote:
Can someone confirm that it is, or is not possible please?



--
Guillermo Rauch
http://devthought.com

mkoistinen

unread,
Feb 21, 2011, 5:17:28 PM2/21/11
to mongoo...@googlegroups.com
Hmmm, do you mean literally 'doc', because I haven't defined a 'doc' anywhere in any of my code.  I assumed that the output above contains 'doc' because that is how a document is defined in Mongoose.  Did I get that wrong?

If you meant 'product', I have now properly declared 'product' as a locally scoped variable with 'var product;' and it makes no difference at all.  The console output I have still doesn't contain an ObjectId or anything remotely like one.  And, if I attempt to console.log(product._id), it just returns 'undefined'.

Can someone (anyone?) confirm that it works for them?

Tony

unread,
Feb 22, 2011, 12:33:03 PM2/22/11
to Mongoose Node.JS ORM
Works fine for me:

var doc = new DocumentModel();
doc.field = "testing";
doc.save(function() {
console.log(doc._id);
});

mkoistinen

unread,
Feb 22, 2011, 6:49:03 PM2/22/11
to mongoo...@googlegroups.com
Thanks, Tony!  Good to know it is supposed to!  I wonder if its not working for me because I'm creating the document from a form post.  Hmmm...

Tony

unread,
Feb 23, 2011, 11:04:17 AM2/23/11
to Mongoose Node.JS ORM
I may also be running an older version as you -- did you try doing it
the way that I posted to see if that works correctly? We could narrow
it down from there.
Reply all
Reply to author
Forward
0 new messages