ko001 ko001 - 5 days ago 10
Javascript Question

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

I am using REST API(express.js and mongodb) and trying to update my document but it's not working. I don't know what is the error but can someone help me out to move forward? I have added my route and controller

Routes:

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


Controller:

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


Data stored like this

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

}


Here is what I am trying to achieve; if
Username, Email, Info
are matched I need to update
article.Info = 'Active';
but this is not working, can someone help me out please?

Answer

From the looks of it, your query is not matching any documents in the collection hence the statement branch which does the update is not being reached, just the else statement as the returned article is null. You can test this by running the raw query in mongo shell on the underlying collection i.e.

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

and see if that returns any matching document. If not, check the Info field from the document returned in this query

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

The best way to go about this within an atomic update that does not require two requests to the server (i.e. one to query the document and the other to write the changes to the server) is to use the findOneAndUpdate api. This will issue a mongodb findAndModify update command which modifies and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option.

Thus your refactored code could follow this pattern:

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

        }
    );
};
Comments