【问题标题】:Edit on Express outputing JSON to database field编辑 Express 将 JSON 输出到数据库字段
【发布时间】:2015-04-28 18:04:01
【问题描述】:

尝试在 Express JS 中创建我的第一个简单 CRUD,但我似乎找不到这个烦人的错误。

当我尝试更新一个字段时,该字段的 JSON 会输出到视图,而不是新数据。

截图:http://i59.tinypic.com/wi5yj4.png

控制器要点:https://gist.github.com/tiansial/2ce28e3c9a25b251ff7c

【问题讨论】:

    标签: json mongodb express controller


    【解决方案1】:

    update 方法用于查找和更新文档,而不返回已更新的文档。基本上,您所做的是查找文档而不更新它们,因为update 函数的第一个参数是搜索条件。在更新其属性后,您需要使用 save 函数来更新现有文档。

    您的代码如下,已修改(未测试):

    //PUT to update a blob by ID
    .put(function(req, res) {
        //find the document by ID
        mongoose.model('Email').findById(req.id, function (err, email) {
            //add some logic to handle err
            if (email) {
                // Get our REST or form values. These rely on the "name" attributes
                email.email = req.body.email;
                email.password = req.body.password;
                email.servico = req.body.servico;
    
                //save the updated document
                email.save(function (err) {
                    if (err) {
                        res.send("There was a problem updating the information to the database: " + err);
                    } 
                    else {
                        //HTML responds by going back to the page or you can be fancy and create a new view that shows a success page.
                        res.format({
                            html: function(){
                                res.redirect("/emails");
                            },
                            //JSON responds showing the updated values
                            json: function(){
                                res.json(email);
                            }
                        });
                    }
                });
            }
        });
    })
    

    【讨论】:

    • 工作就像一个魅力!谢谢你的解释!
    猜你喜欢
    • 2018-10-08
    • 2016-02-13
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 2011-06-11
    • 2019-02-22
    相关资源
    最近更新 更多