modernator modernator - 1 year ago 69
Node.js Question

MongoDB, How to get ObjectId that just created in Embedded document?

I'm creating a Post & Comments, and I designed to post contains comments. "Comments" is embedded document(Object Array) field that contains comment information, and uses "_id" as unique identifier. This is the code(Note that I'm using Node.js with extra mongoDB library) :

db.update('posts', {
_id: new ObjectID(postId)
}, {
$push: {
comments: {
_id: new ObjectID(),
text: comment.text
}) ...

Look at the $push, you can see that I created new ObjectId. It's working well, but I want to send back the _id that just created comment to the client, so make client can erase or edit without page refresh. How do I get the _id that just created embedded document?

Answer Source

How about setting them to variables when you create the ids:

var id1=new ObjectID(postId);
var id2=new ObjectID();

db.update('posts', { _id: id1 },
 { $push:
 { comments: { _id: id2, 
    text:   comment.text } } }) ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download