2

node.jsでMongoDBを使用しています

私が望むのは、コレクション内のドキュメントをアップサートすることです。ドキュメントには、一意の ID、最後にアクセスされた日付を格納する lastAccess フィールド、およびドキュメントの作成時に 0 に設定され、更新時に 1 ずつ増加する timesAccessed フィールドがあります。

私は試した:

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

しかしノードは言う:

MongoError: Modifiers and non-modifiers cannot be mixed

これを行うための正確で安全な方法は何ですか?

4

1 に答える 1

5

値を $set するか、オブジェクト全体を更新/置換する必要があります。したがって、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);
});
于 2013-08-02T15:06:07.093 に答える