乐闻世界logo
搜索文章和话题

How can i save multiple documents concurrently in mongoose?

1个答案

1

In Mongoose, to insert multiple documents simultaneously, you can use the Model.insertMany() method. This method accepts an array as a parameter containing the data for multiple documents to be created. Using insertMany not only minimizes the number of database requests but also enhances the efficiency of data insertion.

Here is an example using the Model.insertMany() method. Assume we have a model named User representing the document structure for user information.

javascript
const mongoose = require('mongoose'); const Schema = mongoose.Schema; // Define the User model's Schema const userSchema = new Schema({ name: String, age: Number, email: String }); // Create the User model const User = mongoose.model('User', userSchema); // Prepare the user data to insert const users = [ { name: 'Alice', age: 25, email: 'alice@example.com' }, { name: 'Bob', age: 30, email: 'bob@example.com' }, { name: 'Carol', age: 22, email: 'carol@example.com' } ]; // Use insertMany to insert multiple documents User.insertMany(users) .then(docs => { console.log('Inserted documents:', docs); }) .catch(err => { console.error('Error inserting documents:', err); });

In this example, we first define a user's Schema and the corresponding model. Then, we create an array containing three user records. Using the User.insertMany() method, we can insert these three user records as documents into the database in a single operation. This method returns a Promise that resolves after all documents have been successfully inserted, providing the inserted documents as the result. If an error occurs during insertion, the Promise is rejected and returns the error information.

This operation is highly useful for bulk data import scenarios, such as during database initialization or handling bulk user registrations.

2024年6月29日 12:07 回复

你的答案