Get id of item push to array in Mongoose

Viewed 930

Post Schema, Comment Schema

const commentSchema = new schema({
    content: {
        type: String,
        required: true,
    }
});

const postSchema = new schema({
    content: {
        type: String,
        required: true,
    },
    timeCreated: {
        type: Date,
        default: Date.now,
    },
    comments: [commentSchema],
});

const Post = mongoose.model('Post', postSchema);

I push comment to array comments in Post by using

const newPost = await Post.findByIdAndUpdate(postId, {
            $push: {
                comments: {
                    content,
                },
            },
        });

I want to the get the id of new comment, but when I console.log it return the Post which not updated. I use postman and see that new comment has been pushed to my post. How can I get the id of new comment ?

1 Answers

An idea by @turivishal : create id comment and push it

const commentId = new mongoose.Types.ObjectId()

await Post.findByIdAndUpdate(postId, {
            $push: {
                comments: {
                    _id: commentId
                    content,
                },
            },
        });

It solved my problem. But welcome any other solution

Related