首页 > 解决方案 > 为 MongoDB 3.6 的 Azure Cosmos DB API 使用 insertMany 时出错

问题描述

尝试 MongoDB insertMany 函数时,我收到以下错误响应。

{"insertError":**{"ok":0,"code":2,"codeName":"BadValue","name":"MongoError"}**,"request":....}

经过一些研究,根据这篇文章,索引似乎是某种类型的错误,但我还没有找到一个实用的解决方案。

目标是将选定的 MongoDB 集合复制到此函数中新创建的集合中。这是代码。

async function createCollection(req, res) {

var body = req.body;
var base = body.baseCollection;
var newCollection = body.newCollection;

try {
  var cursor = await dbo
  .collection(base)
  .find()
  .batchSize(5000)
  .addCursorFlag("noCursorTimeout", true);
  await cursor.rewind();
  var intentsCopy = await cursor.toArray();
  await cursor.close();

} catch (err1) {}

dbo.createCollection(newCollection, function (err, res1) {
if (err) throw err;

dbo.createIndex(newCollection, { "$**": 1 }, function (err, res1) {
  if (err) throw err;

  if (intentsCopy.length < 1) {

    //creating new collection without copying
    res.send({ success: "success", con: con });
    return;
  }

  //creating new collection with copied data

  dbo
    .collection(newCollection)
    .insertMany(intentsCopy, function (err, result) {
      if (err) {
        res.send({ insertError: err, request: intentsCopy });
        throw err;
      }
      if (result.ops.length === intentsCopy.length) {
        res.send({ success: "success", con: con });
      }
    });
  });
});}

标签: node.jsmongodbazure-cosmosdbazure-cosmosdb-mongoapi

解决方案


推荐阅读