私はnodeJsアプリケーションでmongoskinを使用してmongo dbにデータを挿入しています。私は、データベースに文書の配列を挿入し、挿入されたレコードのIDをクライアントに返すという要件があります。データを挿入することはできますが、挿入されたレコードのIDを結果オブジェクトに配置できません。結果にinsertedIdsを見つけるのに役立つ必要があります。私は以下のコードを使用して一括挿入します。Bulk.Insert()-Mongoskinの挿入IDを取得します
db.collection('myCollection', function (err, collection) {
var bulk = collection.initializeUnorderedBulkOp();
for (var i = 0; i < dataArray.length; i++) {
bulk.insert(dataArray[i]);
}
bulk.execute(function (err, result) {
//TODO: return the Ids of inserted records to the client
//Client will use these Ids to perform subsequent calls to the nodejs service
});
});
結果はBatchWriteResult
オブジェクトタイプです。
上記のアプローチを示して? - そうなら、それはとても賢いです。私はそれが好きです! – profesor79
最新のNode.jsドライバを使用している場合は、[** 'getInsertedIds()' **](http://mongodb.github.io/node)を使用して 'Bulk.insertしかし、[** 'BatchWriteResult' **](https://mongodb.github.io/node-mongodb-native/api-mongodb-native/2.1/api/BulkWriteResult.html#getInsertedIds)メソッドを返すので、 generated/batchwriteresult.html)、私が知っている回避策は、 'upsert()'の方法で行って、[** 'getUpsertedIds()' **](https://mongodb.github.io/node- mongodb-native/api-generated/batchwriteresult.html#getupsertedids)メソッドを使用します。説明のために – chridam
thx! – profesor79