如何在express.js中编写查找和更新查询

How to write find and update query in express.js?

本文关键字:查找 更新 查询 express js      更新时间:2023-09-26

我正在使用REST API(express.js和mongodb)并试图更新我的文档,但它不起作用。我不知道是什么错误,但有人能帮我前进吗?我已经添加了我的路线和控制器

路线

app.route('/articleupdation')
         .post(article.updatearticle);

控制器

exports.updatearticle = function(req, res) {
    Article.findOne({
                    Username: 'xx',
                    Email: 'xx@gmail.com',
                    Info: 'Deactivate',
                }, function(err, article) {
                    if (!err && article) {
                            article.Info = 'Active';
                            article.save(function(err) {
                                if (err) {
                                    console.log('not working');
                                } else {
                                    console.log('working');
                                }
                            });
                    } else {
                        console.log('Condtion not matched ');
                        console.log(err);
                    }
                });       
    };

像这样存储的数据

{
    "_id": {
        "$oid": "5799995943d643600fabd6b7"
    },
    "Username": "xx",
    "Email": "xx@gmail.com",
    "Info": "Deactivate",
    "Description": "aajdjdjddjdkjddjdjdhdj",
}

以下是我正在努力实现的目标;如果Username, Email, Info匹配,我需要更新article.Info = 'Active';,但这不起作用,有人能帮我吗?

从外观上看,您的查询与集合中的任何文档都不匹配,因此无法访问执行更新的语句分支,只有返回文章的else语句为null。您可以通过在底层集合(即)上运行mongoshell中的原始查询来测试这一点

db.articles.findOne({
    "Username": "xx",
    "Email": "xx@gmail.com",
    "Info": "Deactivate"
})

看看是否返回任何匹配的文档。如果没有,请检查此查询中返回的文档中的Info字段

db.articles.findOne({
    "Username": "xx",
    "Email": "xx@gmail.com"
})

在不需要向服务器发出两个请求(即一个查询文档,另一个将更改写入服务器)的原子更新中,实现这一点的最佳方法是使用findOneAndUpdateapi。这将发出一个mongodbfindAndModify更新命令,该命令修改并返回单个文档。默认情况下,返回的文档不包括对更新所做的修改。要返回在更新时进行了修改的文档,请使用新选项。

因此,重构后的代码可以遵循以下模式:

exports.updatearticle = function(req, res) {
    Article.findOneAndUpdate(
        { "Username": req.body.username, "Email": req.body.email, "Info": "Deactivate" },
        { "$set": { "Info": "Active" } },
        { "new": true },
        function (err, doc) {
            if (err) { // err: any errors that occurred
                console.log(err);
            } else { // doc: the document before updates are applied if `new: false`
                console.log(doc); // , the document returned after updates if `new  true`
                console.log(doc.Info);
            }
        }
    );
};