Re: How to get the ObjectId of a newly saved document?

5,701 views
Skip to first unread message
Message has been deleted

Darrell Banks

unread,
Feb 19, 2011, 12:06:26 PM2/19/11
to mongoo...@googlegroups.com


Hey there!

I'm pretty new to the game also, I understand your pain. Have you tried to use the "_id" attribute?

Banx

mkoistinen

unread,
Feb 19, 2011, 3:46:45 PM2/19/11
to mongoo...@googlegroups.com
Yes, and it works in all of the other places where I need to use the _id throughout the rest of the app.  Its just in cases where I'm saving a new document that the Mongoose API doesn't appear to have a 'standard' callback with the signature callback(err, document).  I must be missing something...

Siegfried Ehret

unread,
Feb 20, 2011, 4:27:31 AM2/20/11
to mongoo...@googlegroups.com, mkoistinen
You can add this :

BlogPost.virtual('id').get(function () {
  return this._id.toHexString();
}); 

then, calling myPost.id should give you what you want.

YANG Xudong

unread,
Feb 20, 2011, 4:55:06 AM2/20/11
to mongoo...@googlegroups.com
If I'm not misunderstanding your problem, you could do this:

var newEntry = new Entry(...);
newEntry.save(function (err) {
  newEntry._id;    // Hey!
});

=======================
杨旭东 YANG Xudong "Wyverald"
Juntos, unidos, triunfará nuestro deseo de ser el mejor
alias please=sudo
please rm -rf /

mkoistinen

unread,
Feb 20, 2011, 5:27:20 AM2/20/11
to mongoo...@googlegroups.com, mkoistinen
Hi.  Thanks for taking the time to reply.

Your solution looks great if I need to alias id so that it equals _id.  However, my problem is a bit different.  When I create a new document, the ObjectId doesn't exist until the document is saved to the database.  And, unfortunately, I don't see how I can get this ObjectId directly from the save() method.  I can obtain it if I search for the object again, but this isn't ideal, as my document's have only one unique key - the UniqueId.


Let's continue the discussion there. =)

mkoistinen

unread,
Feb 20, 2011, 5:28:35 AM2/20/11
to mongoo...@googlegroups.com
This is precisely what I would like to do, but its not working for me.  Does it work for you?

Also, I've posted a better thread for this here: https://groups.google.com/d/topic/mongoose-orm/ocfUIt5ghLI/discussion

bingomanatee

unread,
Mar 20, 2011, 11:55:57 AM3/20/11
to Mongoose Node.JS ORM

Aaron Heckmann

unread,
Mar 20, 2011, 1:15:33 PM3/20/11
to mongoo...@googlegroups.com
ObjectIds are created upon instantiation:

    var thinger = new Thinger;
    console.error(thinger.id); // 4d8634bbd0d2264d28000001

    thinger.save(function (err) {
       // still works here too
       console.error(thinger.id); // 4d8634bbd0d2264d28000001
    })

Just make sure you store a local ref to your thinger by using the var keyword, else you'll set 'thinger' as a global and get all sorts of unpredictable behavior.
--
Aaron


Reply all
Reply to author
Forward
0 new messages