Skip to content

Instantly share code, notes, and snippets.

@rbatty19
Created February 19, 2022 02:23
Show Gist options
  • Save rbatty19/c7345bb134c59ff6cbae953de9c221f0 to your computer and use it in GitHub Desktop.
Save rbatty19/c7345bb134c59ff6cbae953de9c221f0 to your computer and use it in GitHub Desktop.
Mongoose Util

Hi, I was working with this entity called Developer:

{
  "name": "TEST NAME",
  "slack_id": "2fj9of3wtestid",
  "email": "person@company.io",
  "slack_image": "...URL..."
}

so, to use the insert many and handle the errors, I used the callback err:

Developer.insertMany(dataArray, { ordered: false }, function (err, mongooseDocuments)

err Schema:

{
  name: 'string',
  driver: 'boolean',
  code: 'number',
  writeErrors: 'object', // useful
  result: 'object', // useful
  insertedDocs: 'object' // useful
}

and my solution worked really well:

/**
 *
 * @param {[]} dataArray
 * @typedef {Object} insertManyResult
 * @property {[]} failedInsertions - Array with elements which failed
 * @property {number} nFailedInsertions - quantity of failed insertion elements
 * @property {[]} insertedDocs - Array with elements which were added successfully
 * @property {number} nInsertedDocs - quantity of correct insertion elements
 * @returns {Promise<insertManyResult>} the result of the bulk insertion
 */
exports.addManyDevelopers = async function (dataArray) {
  return new Promise((resolve) => {
    Developer.insertMany(dataArray, { ordered: false }, function (err, mongooseDocuments) {
      if (!err)
        resolve({
          failedInsertions: [],
          nFailedInsertions: 0,
          insertedDocs: mongooseDocuments,
          nInsertedDocs: mongooseDocuments?.length,
        });
      else {
        const errHandleList = JSON.parse(JSON.stringify(err.writeErrors));
        const errHandle = JSON.parse(JSON.stringify(err.result));

        resolve({
          failedInsertions: errHandleList.map((item) => ({
            errorMessage: item.errmsg,
            slack_id: item.op.slack_id,
            name: item.op.name,
          })),
          nFailedInsertions: errHandleList.length,
          insertedDocs: err.insertedDocs,
          nInsertedDocs: errHandle.nInserted,
        });
      }
    });
  });
};

it returns a good response:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment