modernator
modernator

Reputation: 4427

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(),
            author: comment.author,
            email: comment.email,
            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?

Upvotes: 1

Views: 714

Answers (1)

Robert Moskal
Robert Moskal

Reputation: 22553

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

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

db.update('posts', { _id: id1 },
 { $push:
 { comments: { _id: id2, 
    author: comment.author,
    email: comment.email, 
    text:   comment.text } } }) ...

Upvotes: 1

Related Questions