猫鼬的insertMany API中如何访问BulkWriteResult的inserteds数组?

时间:2018-11-07 07:56:36

标签: node.js mongodb mongoose bulkinsert

var f_1=["1","2","3","4"]; var f_2=["1","2","3","4"]; var f_3=["1","two","3","4",]; var f_4=["fname","lname","true","false","1"]; var f_array=["f_1","f_2"]; x=eval(f_array[0]) y=eval(f_array[1]) console.log(x) console.log(y) 中的猫鼬API返回了Promise对象,但我正在使用它的回调版本。

insertMany

当我对let options = { "ordered": true }; MySchema.insertMany(documents, options, function (error, docs) { if(error) { // i need insertedIds array here } else { // do someting } }); 对象进行字符串化时,可以看到如下所示的JSON:

error

但是当我尝试获取{ "ok":1, "writeErrors":[ "code":11000, "index":1, // there will be some more failure details here ], "writeConcernErrors":[], "insertedIds":[ { "index":0, "_id":"5be183914d0c761eeadda8c4" }, { "index":1, "_id":"5be183914d0c761eeadda8c5" }, { "index":2, "_id":"5be183914d0c761eeadda8c6" } ], "nInserted":1, "nUpserted":0, "nMatched":0, "nModified":0, "nRemoved":0, "upserted":[] } 数组时,它将返回insertedIds。我做了一些研究,发现返回的undefined对象实际上不是JSON对象,而是与errorBulkWriteResult相关的东西。

  

那么,现在如何获取BulkWriteError数组中的值?请帮忙。

P.S .:使用猫鼬版本:^ 5.2.17

1 个答案:

答案 0 :(得分:0)

由于result.insertedIds是吸气剂,请尝试使用let insertedIds = error.result.getInsertedIds()let insertedIds = JSON.parse(JSON.stringify(error.result)).insertedIds;