首页 > 解决方案 > 如何更新嵌套模型中的文本 - MERN 堆栈

问题描述

我刚刚开始学习 MERN 堆栈,但在使用 Express/Node 更新模型中的文本时遇到问题。我试图寻求帮助并访问了在模型中更新模型 如何在模型中嵌套模型,但它们并不是我想要的。

我正在使用 2 个模型,评论模型嵌入到猫模型中,就像这样。这是评论模型

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const commentSchema = new Schema(
  {
    user_id: { type: String, required: true },
    cat_id: { type: String, required: true },
    text: {
      type: String,
      min: [3, "Comment cannot be too short"],
    },
    email: { type: String, required: true },
  },
  { timestamps: true }
);

const Comment = mongoose.model("Comment", commentSchema);
module.exports = Comment;

这个评论模型在猫模型中

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Comment = require("./comments.js");

const catSchema = new Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
      min: [2, "Cat name minimum of 2 characters."],
    },
    description: { type: String, required: true },
    image: { type: String },
    gender: { type: String, required: true },
    cage: { type: String, required: true },
    adoptable: { type: String, required: true },
    comments: [Comment.schema],
  },
  { timestamps: true }
);

const Cat = mongoose.model("Cat", catSchema);
module.exports = Cat;

在我的控制器中,当我更新评论时,我也需要更新 cat 模型中的相应评论,但我无法这样做。我尝试定位特定的猫 foundCat,但我无法使用 foundCat.comments.id(req.params.id) 访问评论

奇怪的是,当我控制台日志“foundCat.comments.id”时,它告诉我这是一个函数?所以我不知道为什么我无法访问和更新该文本...

这是我更新评论的代码:注意!有问题的部分位于末尾,查找“Cat.findOne”

// For updating comment
const updateComment = async (req, res) => {
  // if there is no req.body, return error
  if (!req.body) {
    return res.status(400).json({
      success: false,
      error: "You must provide a body to update",
    });
  }

  // req.body exists, so find the comment by id and then update
  Comment.findOne({ _id: req.params.id }, (err, comment) => {
    if (err) {
      return res.status(404).json({
        err,
        message: "Comment not found!",
      });
    }
    console.log(req.body);
    // update the comment details
    comment.text = req.body.text;
    // save the updated comment
    comment
      .save()
      .then(() => {
        // return json response if successful
        return res.status(200).json({
          success: true,
          id: comment._id,
          message: "Comment updated!",
        });
      })
      .catch((error) => {
        return res.status(404).json({
          error,
          message: "Comment not updated!",
        });
      });
    // now update the comment entry for the cat too
    Cat.findOne({ _id: comment.cat_id }, (err, foundCat) => {
      console.log("This doesnt work", foundCat.comments.id(req.params.id));
      foundCat.save((err, updatedCat) => {
        console.log(updatedCat);
      });
    });
  });
};

猫中的评论示例: 在此处输入图像描述

标签: node.jsmongodbexpressmongoose

解决方案


获取评论后,您应该更新 cat 实例。

尝试像这样更改您的代码(使用async wait):

const updateComment = async (req, res) => {
  // if there is no req.body, return error
  if (!req.body) {
    return res.status(400).json({
      success: false,
      error: 'You must provide a body to update',
    });
  }

  try {
    // req.body exists, so find the comment by id and then update
    const comment = await Comment.findById(req.params.id);
    if (!comment) {
      return res.status(404).json({
        err,
        message: 'Comment not found!',
      });
    }
    // update the comment details
    comment.text = req.body.text;
    // save the updated comment
    await comment.save();

    // now update the comment entry for the cat too
    const cat = await Cat.findById(comment.cat_id);
    const otherCatComments = cat.comments.filter((c) => c._id !== comment._id);
    cat.comments = [...otherCatComments, comment];

    await cat.save();

    res.status(200).json({
      success: true,
      id: comment._id,
      message: 'Comment updated!',
    });
  } catch (err) {
    res.status(404).json({
      error,
      message: 'Comment not updated!',
    });
  }
};

推荐阅读