填充方法不填充我的评论数组

Populate method not populating my comment array

这是我在猫鼬中创建的 PostSchema,我在 post 和评论中都提到了用户 table。

 const PostSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  text: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'users',
  },
  comment: [
    {
      user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'users',
      },
      text: {
        type: String,
        require: true,
      },
      date: {
        type: Date,
        default: Date.now,
      },
    },
  ],
});

我试图做的是让 post 在我调用它时更新 ref 上的用户元素,以提供用户 ID 和名称。

    const posts = await Post.find().populate('user', 'name');

这适用于此,但它对评论中的每个用户引用都没有同样的效果。我是不是做错了什么?

编辑:

const newComment = {
        user: user._id,
        text: req.body.text,
      };
      post.comment.unshift(newComment);
      await post.save();

这是添加评论的代码,user._id是当前登录用户的objectId。

我什至试过制作

        user: user._id,

user: req.user.id,


const newPost = new Post({
        text: req.body.text,
        title: req.body.title,
        user: req.user.id,
      });

      await newPost.save();

这是newPost的代码,同样req.user.id是当前登录的ID。

编辑:

这是用户架构

常量猫鼬=要求('mongoose');

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

module.exports = mongoose.model('users', userSchema);

请查看如何使用填充

let articles = await Product.find({ _id: { $in: items } })
    .populate("brand")
    .populate("wood")
    .exec();
Story.
  find().
  populate({ path: 'fans', select: 'name' }).
  populate({ path: 'fans', select: 'email' });
// The above is equivalent to:
Story.find().populate({ path: 'fans', select: 'email' });

d

不久前我找到了这个问题的解决方案,但我想我会在这里更新它。

const posts = await Post.find().populate({select:"comments":populate:{path:'users'}});

select 从架构中选择路径,然后我们可以嵌套另一个填充路径以指定嵌套选项。