4

Node.jsネイティブドライバーを使用しています。以下は正常に動作します

db.collection("test").insert({hello:'world_safe'}, {safe: true}, function(err, result) {
    if (err) throw err;
    db.collection("test").insert({hello:'world_safe'}, {safe: true}, function(err, result) {
        if (err) throw err;
        db.close();
    });
});

私はデータベースで次のものを取得します

{"hello": "world_safe"、 "_id":ObjectId( "4fe978c8b8a5937d62000001")} {"hello": "world_safe"、 "_id":ObjectId( "4fe978c8b8a5937d62000002")}

しかし、私が次のように微調整すると

var json = {hello:'world_safe'};
db.collection("test").insert(json, {safe: true}, function(err, result) {
    if (err) throw err;
    db.collection("test").insert(json, {safe: true}, function(err, result) {
        if (err) throw err;
        db.close();
    });
});

次のエラーが発生します

MongoError:E11000重複キーエラーインデックス:

エラーメッセージが表示されるのはなぜですか?

4

2 に答える 2

5

ドライバーは最初の挿入でオブジェクトに_idキーを追加するjsonため、2番目の挿入でjson_id魔女が複製されます。

https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js

// Add id to each document if it's not already defined
    if (!(Buffer.isBuffer(doc)) && doc['_id'] == null && self.db.forceServerObjectId != true) {
      doc['_id'] = self.pkFactory.createPk();
    }
于 2012-06-26T09:00:09.353 に答える
0

解決策がそれよりも簡単であることを除いて、私はCDに同意します。

/* ... before insert */

if(typeof(collection._id) != 'undefined')
        delete collection._id;

/* ... now insert */
于 2013-09-03T04:05:42.290 に答える