Question

I'm using MongoDB in node.js

What I would like is to upsert a document in a collection. The document has an unique ID, a lastAccess field, which stores the date of the last time accessed, and a timesAccessed field, which should be set to 0 on document creation and incremented by 1 if updating.

I tried:

// coll is a valid collection
coll.update(
    {user: accountInfo.uid},
    {user: accountInfo.uid,
     lastAccess: new Date(),
     $inc: {timesAccessed: 1},
     $setOnInsert: {timesAccessed: 0}
    },
    {upsert: true, w: 1},
    function(err, result) {
        if (err) throw err;
        console.log("Record upserted as " + result);
    });

but node says:

MongoError: Modifiers and non-modifiers cannot be mixed

What is a coincise and safe way to do this?

Was it helpful?

Solution

You should either $set the values or update/replace the whole object. So either update(find_query, completely_new_object_without_modifiers, ...) or update(find_query, object_with_modifiers, ...)

Plus, you cannot $set and $setOnInsert with the same field name, so you will start counting from 1 :) Oh, and you don't need to add the find_query items to the update_query, they will be added automatically.

Try:

col1.update( {
  user: accountInfo.uid
}, {
  $set: {
    lastAccess: new Date()
  }
  $inc: {
    timesAccessed: 1
  }
}, {
  upsert: true,
  w: 1
}, function(err, result) {
  if(err) {
    throw err;
  }
  console.log("Record upsert as", result);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top