Categories
JavaScript Answers

How to do batch insert with Node.js Mongoose?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *