在猫鼬反向填充期间如何填充objectIds

时间:2019-12-12 19:10:00

标签: mongodb mongoose mongoose-schema mongoose-populate

 const PostSchema = new mongoose.Schema(
  {
    title: String,
    image: String,
    description: String,
    createdAt: {
      type: Date,
      default: Date.now
    },
    user: {
      type: mongoose.Schema.ObjectId,
      ref: 'User',
      required: true
    },
    likeCount: {
      type: Number,
      default: 0
    },
    shared: {
      type: String,
      enum: ['public', 'private']
    },
    like: [
      {
        type: mongoose.Schema.ObjectId,
        ref: 'User'
      }
    ]
  },
  {
    toJSON: { virtuals: true },
    toObject: { virtuals: true }
  }
);

    PostSchema.virtual('comments', {
  ref: 'Comment',
  localField: '_id',
  foreignField: 'post',
  justOne: false
});


const CommentSchema = new mongoose.Schema({
  comment: {
    type: String,
    required: true,
    maxlength: 256,
    trim: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  user: {
    type: mongoose.Schema.ObjectId,
    ref: 'User',
    required: true
  },
  post: {
    type: mongoose.Schema.ObjectId,
    ref: 'User',
    required: true
  }
});


    let posts = await Post.find({})
      .populate('user')
      .populate('comments')
      .sort('-_id')
      .limit(1);

当我在帖子模式中填充评论虚拟类型时,我也想填充与该评论关联的用户字段。我想向前端显示用户数据,因此我需要能够填充它。有什么办法吗?我一直在寻找答案的时间,但找不到。答案可能很简单,但我找不到它,所以请帮助我。

0 个答案:

没有答案