在Express上输出JSON输出到数据库字段

时间:2015-04-28 18:04:01

标签: json mongodb express controller

尝试在Express JS中创建我的第一个简单的CRUD,我似乎无法找到这个烦人的bug。

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

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

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

1 个答案:

答案 0 :(得分:0)

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);
                        }
                    });
                }
            });
        }
    });
})