使用MongoDB升级文档,递增字段并将其设置为0(如果不存在)

jan*_*nce 2 mongodb node.js node-mongodb-native

我在node.js中使用MongoDB

我想要的是在一个集合中插入一个文档.该文档具有唯一的ID,lastAccess字段,用于存储上次访问的日期,以及timesAccessed字段,在创建文档时应设置为0,如果更新则应增加1.

我试过了:

// 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);
    });
Run Code Online (Sandbox Code Playgroud)

但节点说:

MongoError: Modifiers and non-modifiers cannot be mixed
Run Code Online (Sandbox Code Playgroud)

什么是巧妙和安全的方法来做到这一点?

ran*_*nel 5

您应该$设置值或更新/替换整个对象.因此,无论update(find_query, completely_new_object_without_modifiers, ...)update(find_query, object_with_modifiers, ...)

另外,你不能用$ set和$ setOnInsert使用相同的字段名,所以你将从1开始计数:)哦,你不需要将find_query项添加到update_query,它们将自动添加.

尝试:

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);
});
Run Code Online (Sandbox Code Playgroud)