首页 > 解决方案 > Mongoose 在创建时自动填充

问题描述

我正在使用 mongoose 插件autopopulate从单独的集合中填充文档。这是一个简化的架构:

const PostSchema = new Schema(
  {
    user: {
      type: Schema.Types.ObjectId,
      ref: 'user',
      required: true,
      autopopulate: {
        select: ['firstName', 'lastName', 'email', 'username']
      }
    },
    comment: { type: String }
  }
)

现在,当我创建一个帖子时

const post = await Post.create({ user, comment });

即使它显示在数据库和后续查询中,它也会为填充的用户返回 null。我已经使用了该{ new: true }选项,findByIdAndUpdate但它似乎不适用于create. 关于如何创建以返回填充的文档的任何想法?

标签: javascriptmongodbmongoosemongoose-populate

解决方案


推荐阅读