mradfo21 mradfo21 - 8 months ago 40
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

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

SyntaxError: Unexpected token {

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


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

Try this instead:

    {keyword: key},
    {$inc: {score: 1}},
    {upsert: true, safe: false},
        if (err){
            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().