【问题标题】:Mongoose Update route shows the old value with .findByIdAndUpdate()Mongoose 更新路线使用 .findByIdAndUpdate() 显示旧值
【发布时间】:2018-01-16 20:25:39
【问题描述】:

我有一个引用 url /campgrounds/:id/comments/:comment_id 的评论更新路线,我在 app.js 中将它用作 app.use("/campgrounds/:id/comments", commentsRoutes);

cmets 指的是露营地。这是评论更新路线:

router.put("/:comment_id", function (req, res) {
    Comment.findByIdAndUpdate(req.params.comment_id, req.body.comment, {new: true})
        .exec(function(err, updatedComment){
            if (err) {
                res.redirect("back");
            } else {
                console.log("this is the updated comment" + updatedComment);
                res.redirect("/campgrounds/" + req.params.id);
            }
        });
});

我使用 mongoose 通过 url params id 查找评论,查找评论中的更改并尝试更新并重定向到 /campgrounds/:id(露营地显示路线)

我不知道为什么,但是这段代码不起作用:如果我记录了 updatedComment 我有:

this is the new comment 
{ author: { id: 5a5dc000af7fbb1138a27e33, username: 'patata' },
  _id: 5a5e0845f62da603900ab0d5,
  text: 'updated text field',
  __v: 0 }

res.redirect 有效,但页面显示评论的旧值,如果我在露营地显示路线中记录露营地,我有以下输出:

{ author: { id: 5a5dc000af7fbb1138a27e33, username: 'patata' },
  comments: 
   [ { author: [Object],
       _id: 5a5e0845f62da603900ab0d5,
       text: 'old text field',
       __v: 0 } ],
  _id: 5a5e083af62da603900ab0d4,
  name: 'Armando',
  image: 'https://i.pinimg.com/originals/2e/b7/e2/2eb7e206036f11c94ed0cac8fb1fc05e.jpg',
  description: 'lalala',
  __v: 1 }

请注意,评论 ID 是相同的 (5a5e0845f62da603900ab0d5)。即使我刷新页面,评论总是旧的...

这是露营地表演路线:

//SHOW
router.get('/:id', function (req, res) {
    //find correct campground ID
    Campground.findById(req.params.id).populate("comments").exec(function (err, foundCampground) {
        if (err) {
            console.log(err);
        } else {
            // render the show template
            console.log(foundCampground);
            res.render('campgrounds/show', {campground:foundCampground});
        }
    });
});

我该如何解决这个问题?

谢谢

编辑:@AngelSalazar 这是我的露营地模型:

var campgroundSchema = new mongoose.Schema({
    name: String,
    image: String,
    description: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    },
    comments: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Comment"
    }]
});

module.exports = mongoose.model("Campground", campgroundSchema);

这是评论模型:

var mongoose = require("mongoose");

var commentSchema = new mongoose.Schema({
    text: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    }
});

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

所以我必须尝试找到Campground Id,然后找到campground cmets并从body req中设置评论的新值,然后保存Comment和Campground?

我试试这个代码:

router.put("/:comment_id", function (req, res) {
    Comment.findByIdAndUpdate(req.params.comment_id,
        {$set: {text: req.body.comment.text}},
        {new: true},
        function (err, updatedComment) {
            if (err) {
                res.redirect("back");
                console.log("error");
            } else {
                Campground.findByIdAndUpdate(req.params.id, 
                    {$set: {"comments.text": updatedComment.text}}, 
                    {new: true},
                    function (err, foundCampground) {
                        if (err) {
                            res.redirect("/campgrounds/" + req.params.id); // redirect to show page correctly
                            console.log("error"); // log error
                            console.log(foundCampground); // log undefined
                        } else {
                            res.redirect("/campgrounds/" + req.params.id);
                            console.log("ok");
                            console.log(foundCampground);
                        }
                    });
            }
        });
});

奇怪的是,现在更新完成了,但是重定向到露营地展示页面的路由只有在遇到错误状态时才有效!控制台显示错误,但露营地已更新,我现在不知道为什么,但对我来说很奇怪......

【问题讨论】:

  • req.body.comment 中的注释是一个对象吗?,您应该传递的内容类似于 Comment.findByIdAndUpdate(req.params.comment_id, { $set : { text : req.body.comment } }, {new: true})
  • 是的,是一个对象,我尝试Comment.findByIdAndUpdate(req.params.comment_id, { text : req.body.comment.text }, {new: true})但不更新评论
  • 第二个参数应该是 { $set : { text : req.body.comment.text } }
  • 尝试过(见下文),但仍然无法正常工作。如果我得到编辑页面,我在正确的字段中有新的 comment.text 值,但是当我重定向到显示页面时出现问题
  • 你能展示你的模型吗?我相信评论是其他文档的子文档,如果是这种情况,您首先必须获取其他文档,查询其 cmets,从中您应该找到要更新的评论修改它然后保存文档(没有子文档)

标签: javascript node.js mongodb express mongoose


【解决方案1】:

您必须使用$set 来定义要更新的内容。

请查看 Documents 页面上的 mongoose 文档,Update 项: http://mongoosejs.com/docs/documents.html

【讨论】:

  • 我尝试..., { $set: { text: req.body.comment.text }}, ...,但我有同样的错误
【解决方案2】:

@Mayank Yadav:我没有找到使用 mongoose 5.x 的方法,我不得不降级到 4.11.9 版本。在这种情况下适用于我的代码是:

评论放置路线

// Update for  "mongoose": "^4.11.9",
router.put("/:comment_id", function(req, res){
    Comment.findByIdAndUpdate(req.params.comment_id, req.body.comment, function(err, comment){
        if(err){
            console.log(err);
            res.render("edit");
        } else {
            res.redirect("/campgrounds/" + req.params.id);
        }
    });
});

但是,请检查此页面中的 MongoDB 兼容性:http://mongoosejs.com/docs/compatibility.html,因为您可能必须使用 usePushEach 更改模型:

评论模型

var mongoose = require("mongoose");

var commentSchema = new mongoose.Schema({
    text: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    }
}, { usePushEach: true });

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

希望对您有所帮助。再见

【讨论】:

    猜你喜欢
    • 2020-08-12
    • 2021-10-23
    • 2014-02-19
    • 2013-08-14
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 2018-08-13
    • 2018-11-25
    相关资源
    最近更新 更多