mradfo21 mradfo21 - 6 months ago 12
Node.js Question

Node.js MongoDB Upsert update

I'm writing a little application which scores keywords. So if "beirut" and "education" get entered in, if they haven't been seen before, I want to create a mongo entry, and give them a score of 1. If they have, I want to increment their score by one. I'm trying to do this with one update command, but I think I might be doing it wrong.


  • Ranking is the object representing the database

  • "key" is the keyword



rankingdb.update(
{keyword:key},
{keyword:key, {$inc:{score:1}}},
{upsert:true, safe:false},
function(err, data) {
if (err) {
console.log(err);
}
else {
console.log("score succeeded");
}
}
);


SyntaxError: Unexpected token {


Can you not create a brand new document with an increment?

Answer

Your general approach is right, but as the error message suggests, you've got a syntax problem in your code.

Try this instead:

rankingdb.update(
    {keyword: key},
    {$inc: {score: 1}},
    {upsert: true, safe: false},
    function(err,data){
        if (err){
            console.log(err);
        }else{
            console.log("score succeded");
        }
    }
);

When an upsert needs to create a new object it combines the fields from the selector (first parameter) and the update object (second parameter) when creating the object so you don't need to include the keyword field in both.

Note that update() is deprecated in the 2.0 driver, so you should now use either updateOne() or updateMany().