How to do batch insert with Node.js Mongoose?

Sometimes, we want to do batch insert with Node.js Mongoose.

In this article, we’ll look at how to do batch insert with Node.js Mongoose.

How to do batch insert with Node.js Mongoose?

To do batch insert with Node.js Mongoose, we can use the insertMany method.

For instance, we write

const rawDocuments = [
  /* ... */
];

const mongooseDocuments = await Book.insertMany(rawDocuments)

to call Book.inseertMany with the rawDocuments array with the plain objects we want to insert as documents into the books collection.

Then we get the inserted documents from the resolved value of the returned promise as an array and assign that to mongooseDocuments.

Conclusion

To do batch insert with Node.js Mongoose, we can use the insertMany method.