小编Fel*_*lix的帖子

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

帖子架构、评论架构

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?

mongoose mongodb node.js

2
推荐指数
1
解决办法
1246
查看次数

标签 统计

mongodb ×1

mongoose ×1

node.js ×1