简体   繁体   English

MEAN应用程序更新功能

[英]MEAN Application Update Function

I am trying to write a MEAN application update function but the update will not save to the MongoDB database. 我正在尝试编写MEAN应用程序更新功能,但是更新不会保存到MongoDB数据库中。 I am trying to update the title of my document only. 我正在尝试仅更新文档的标题。 Below is the function I have written. 下面是我编写的函数。

router.updateJob = function (req, res) {

    Job.findById(req.params.id, function(err, job) {
        if (err)
            res.send(err);
        else {

            var oldTitle = job.title;
            var newTitle = req.body.title;

            job.save(function (err) {
                if (err)
                    res.send(err);
                else
                    job.title = newTitle;
                    res.json({updatedTitle: job.title});
            });
        }
    });
};

I am sending the new title in a JSON string using the Web Storm API testing tool. 我正在使用Web Storm API测试工具以JSON字符串发送新标题。 The string I am sending looks like the one below: 我发送的字符串如下所示:

{"title" : "Updated Title"}

The response I am getting from the API is shown below, you can see that the title is showing as Updated Title. 我从API收到的响应如下所示,您可以看到标题显示为“更新标题”。 But when I go into the database it is showing as the original title which is Test. 但是当我进入数据库时​​,它显示为原始标题,即Test。

{"updatedTitle":"Updated Title"}

What do I have to do to get the new title to save to the database? 我要怎么做才能将新标题保存到数据库? If there is any other information you need to help figure this out please don't hesitate to ask. 如果您需要其他任何信息以帮助解决此问题,请随时询问。

Try using the findByIdAndUpdate method. 尝试使用findByIdAndUpdate方法。 So: 所以:

router.updateJob = function (req,res) {
  Job.findByIdAndUpdate(req.params.id, req.body, {new:true}, function(err, doc) {
     if(err)
         return res.json(err);
     else
         return res.json(doc);
  });
};

It's actually job.save(callback). 实际上是job.save(callback)。 Assignment should be done before the .save() 分配应该在.save()之前完成

router.updateJob = function (req, res) {

Job.findById(req.params.id, function(err, job) {
    if (err)
        res.send(err);
    else {
        var newTitle = req.body.title;

        job.title = newTitle;

        job.save(function (err) {
            if (err)
                res.send(err);
            else
                res.json({updatedTitle: job.title});
        });
    }
 });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM