2

I get the following error response when attempting the MongoDB insertMany function.

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

After some research, it seems to be some type of error with indexing according to this post, but I haven't found a practical solution.

The goal is to copy a selected MongoDB collection into the newly created collection in this function. Here is the code.

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

0 Answers0