【发布时间】:2021-10-31 10:46:24
【问题描述】:
我刚开始学习 MERN 堆栈,但在使用 Express/Node 更新模型中的文本时遇到问题。我试图寻求帮助并访问了Update a model within a model How to Nest Models within a Model 但它们并不是我想要的。
我正在使用 2 个模型,将 cmets 模型嵌入到 cat 模型中,就像这样。这是评论模型
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.cmets.id(req.params.id) 访问评论
奇怪的是,当我控制台记录“foundCat.cmets.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.js mongodb express mongoose