【问题标题】:Populate method not populating my comment array填充方法未填充我的评论数组
【发布时间】:2020-09-01 04:55:21
【问题描述】:

这是我在 mongoose 中创建的 PostSchema,我在帖子和评论中都引用了 users 表。

 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,
      },
    },
  ],
});

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

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

这适用于这个,但它对评论中的每个用户 ref 没有做同样的事情。我是不是做错了什么?

编辑:

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。

编辑:

这是用户架构

const mongoose = require('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);

【问题讨论】:

    标签: mongodb express mongoose mern


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      请查看如何使用填充

      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

      【讨论】:

      • 它对我不起作用,我什至尝试按照猫鼬文档中多级人口的建议进行操作。
      • 你能分享一下用户架构吗
      • 我已将用户架构添加到帖子@Adepitan Oriyomi
      • 当导出你的架构时,它应该是单数使用 module.exports = mongoose.model('User', userSchema);相反用户:{类型:mongoose.Schema.Types.ObjectId,参考:'用户',},
      • 我不明白你的意思。我在该代码中添加了创建对用户集合的引用,以使用用户集合中的对象 ID 填充用户字段
      猜你喜欢
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      • 2019-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多