Node.js Mongoose - 模型更新中的模型

Node.js Mongoose - model in model update

我有 1 个博文模型:

const blogSchema= new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
  name: {
    type: String,
    required: true,
    max: 50,
    min: 6,
  },
  description: {
    type: String,
    required: true,
    max: 1024,
    min: 25,
  },
  date: {
    type: Date,
    default: Date.now,
  },
  comment: [commentSchema],
});

这里的重要部分是最后一个字段评论。为此,我有另一个模式:

    const commentSchema = new mongoose.Schema({
      date: {
        type: Date,
        default: Date.now,
      },
      comment: {
        type: String,
        max: 1024,
        min: 5,
      },
      userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
      },
    });

一般在创建post的时候,就可以添加评论了。在一个单独的文件中 User.js 我有用户的模型:

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    unique: true,
    required: true,
    max: 255,
    min: 6,
  },
  email: {
    type: String,
    unique: true,
    required: true,
  },

  password: {
    type: String,
    required: true,
    min: 6,
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

如何将它们连接起来一起工作。我有一个端点,其中所有 post 都是可见的(无论哪个用户提供它们)。我希望 1 位用户能够对另一位用户发表评论 post,并且他的名字出现在评论下方。

所以我可以如何创建任何想法:

  1. 将在 blogSchema 的评论字段中存储评论的端点
  2. 用户将被记录在commentSchema

对于 blogPosts 模型,您需要使用类型对象 ID 和 ref:"comment"

将评论数组存储为对评论的引用
comment: [{
type: mongoose.Schema.Types.ObjectId,
ref: "commentSchema",
}]

现在,当评论添加到 post 时,将评论文档 ID 添加到 blogpost->comment 数组。 要获取博客上的评论post,请使用聚合或填充与博客相关的评论post。

我的做法:

另一个文件中的分隔评论模型:

  const mongoose = require("mongoose");
    
    const commentSchema = new mongoose.Schema({
      date: {
        type: Date,
        default: Date.now,
      },
      comment: {
        type: String,
        max: 1024,
        min: 5,
      },
      userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
      },
    });
    
    module.exports = mongoose.model("Comment", commentSchema);

按照 Mohit Gupta 在其回答中的建议更改评论字段:

const mongoose = require("mongoose");

const blogSchema = new mongoose.Schema({
  //OTHER FIELDS ARE HERE.....
  comment: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Comment",
    },
  ],
});

module.exports = mongoose.model("Blog", blogSchema);

然后我做了这样的路线:

//COMMENT
router.post("/comment/:post", verify, async (req, res) => {

  const { comment } = req.body;
  if (!comment) {
    return res
      .status(422)
      .send({ error: "Must provide comment with at least 5 symbols" });
  }

  try {
    const newComment = new Comment({ comment, userId: req.user._id });
    await newComment.save();
    const update = {
      $push: {
        comment: newComment,
      },
    };
    const post= await Blog.findOneAndUpdate(
      { _id: req.params.post },
      update
    );

    res.send(post);
  } catch (err) {
    res.status(422).send({ error: err.message });
  }
});