获取 Mongoose 中推送到数组的项目 ID

Fel*_*lix 2 mongoose mongodb node.js

帖子架构、评论架构

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);
Run Code Online (Sandbox Code Playgroud)

comments我使用以下方法将评论推送到 Post 中的数组

const newPost = await Post.findByIdAndUpdate(postId, {
            $push: {
                comments: {
                    content,
                },
            },
        });
Run Code Online (Sandbox Code Playgroud)

我想获取新评论的 id,但是当我console.log返回未更新的帖子时。我使用邮递员并看到新评论已推送到我的帖子中。如何获取新评论的id?

Fel*_*lix 5

@turivishal的一个想法:创建 id 评论并推送它

const commentId = new mongoose.Types.ObjectId()

await Post.findByIdAndUpdate(postId, {
            $push: {
                comments: {
                    _id: commentId
                    content,
                },
            },
        });
Run Code Online (Sandbox Code Playgroud)

它解决了我的问题。但欢迎任何其他解决方案