Mongoose Model.create() API
Last Updated :
21 Mar, 2025
In Node.js applications, Mongoose provides an effective way to interact with MongoDB, allowing developers to define models and schemas to store and retrieve data. One of the essential methods provided by Mongoose is Model.create(), which is used to create one or more documents in a MongoDB collection.
The Model.create() method internally triggers the save() method for document creation. This function is extremely useful when we need to insert data into the database quickly and efficiently, either for a single document or multiple documents at once.
What is Mongoose Model.create()?
The Model.create() method in Mongoose is designed to simplify document creation in MongoDB. When invoked, this method allows us to create a single or multiple documents in a specified collection. It accepts a range of parameters, including the document(s) to be inserted, options for customization, and an optional callback function for handling the response. This method returns a Promise, which makes it easy to handle asynchronous operations in JavaScript.
Syntax:
Model.create(docs, options, callback)
Parameters:
- docs (Required): An object or an array of objects representing the data to be inserted into the collection.
- options (Optional): An object that can include various options such as validation, timestamps, etc.
- callback (Optional): A callback function that will be called once the operation is complete.
Return Value:
- The Model.create() method returns a Promise that resolves to the created document(s). If the operation fails, it will reject the promise with an error.
How to Use Mongoose Model.create() Method?
Step 1: Setting up a Node.js application with Mongoose
To use the Model.create()
method in Mongoose, we first need to set up a Node.js application. Start by initializing your project using npm init
. This will create a package.json
file for managing your project dependencies and configurations. Run the following command in your terminal:
npm init
Step 2: Install Mongoose
After setting up the project, we need to install the Mongoose module, which allows interaction with a MongoDB database. To install it, run the following command in your project directory:
npm install mongoose
Project Structure: The project structure will look like this:
 This will add Mongoose as a dependency to your project, allowing us to use its features such as the Model.create()
method for creating documents in MongoDB.
Example 1: Creating a Single Document in MongoDB
In this example, We have established a database connection using mongoose and defined model over customerSchema, having two columns "name", and "orderCount". In the end, we are creating a single document on the Customer model.
Code:
// Require mongoose module
const mongoose = require('mongoose');
// Set Up the Database connection
mongoose.connect(
'mongodb://localhost:27017/geeksforgeeks', {
useNewUrlParser: true,
useUnifiedTopology: true
})
// Defining customerSchema schema
const customerSchema = new mongoose.Schema(
{ name: String, orderCount: Number }
)
// Defining customerSchema model
const Customer = mongoose.model(
'Customer', customerSchema);
// creating document using create method
Customer.create({ name: 'Rahul', orderCount: 5 })
.then(result => {
console.log(result)
})
Steps to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
{
name: 'Rahul',
orderCount: 5,
_id: new ObjectId("6304e68407a431f560473ac2"),
__v: 0
}
GUI Representation of the  Database using Robo3T GUI tool
Example 2: Creating Multiple Documents in MongoDB
In this example, We have established a database connection using mongoose and defined model over customerSchema, having two columns "name", and "orderCount". In the end, we are creating multiple documents at a time on the Customer model.
Code:
// Require mongoose module
const mongoose = require('mongoose');
// Set Up the Database connection
mongoose.connect(
'mongodb://localhost:27017/geeksforgeeks', {
useNewUrlParser: true,
useUnifiedTopology: true
})
// Defining customerSchema schema
const customerSchema = new mongoose.Schema(
{ name: String, orderCount: Number }
)
// Defining customerSchema model
const Customer = mongoose.model(
'Customer', customerSchema);
// Creating document using create method
Customer.create([{
name: 'Customer2',
orderCount: 10
},
{ name: 'Customer3', orderCount: 20 }])
.then(result => {
console.log(result)
})
Steps to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
[
{
name: 'Customer2',
orderCount: 10,
_id: new ObjectId("6304e7c8c21ca86f5ea6fce3"),
__v: 0
},
{
name: 'Customer3',
orderCount: 20,
_id: new ObjectId("6304e7c8c21ca86f5ea6fce4"),
__v: 0
}
]
GUI Representation of the  Database using Robo3T GUI tool
Troubleshooting Common Issues with Model.create()
1. Error Handling: Always ensure that we handle errors correctly when using the Model.create() method. Use .catch()
or try...catch
to capture any issues, such as validation errors or database connection issues.
2. Validation Issues: If your schema includes validation rules (e.g., required fields), ensure that the data you pass to Model.create() adheres to these rules. Otherwise, Mongoose will throw an error.
3. Handling Promises: Since Model.create() returns a promise, remember to either use await
with async
functions or .then()
and .catch()
for promise handling.
Best Practices for Using Mongoose Model.create()
1. Use Proper Error Handling: Always handle errors and exceptions in your application to avoid unexpected crashes. Mongoose will reject the promise if any issues arise during document creation.
2. Validate Data Before Insertion: If your schema includes validation rules (e.g., required fields, data types), ensure your data adheres to these rules to avoid validation errors.
3. Batch Insertion: When inserting multiple documents, use Model.create() for better performance compared to inserting documents one by one.
4. Avoid Unnecessary Callback: Mongoose Model.create() returns a promise by default, so you generally don’t need to use a callback unless you want to support legacy code or need additional flexibility.
Conclusion
The Mongoose Model.create() method is a powerful tool for creating documents in MongoDB. Whether we need to insert a single document or multiple documents at once, Mongoose makes it simple and efficient. By understanding its syntax, options, and practical applications, you can leverage this method to streamline your data insertion process in Node.js applications. This method not only simplifies the code but also helps improve performance when working with MongoDB in Node.js.
Similar Reads
Mongoose Document Model() API The Mongoose Document APIModel() method of the Mongoose API is used on the Document model. It allows to create a MongoDB class. Using this method we can create model that can interact with MongoDB for all operations. Let us understand the APIModel() method using an example. Syntax: mongoose.model( d
3 min read
Mongoose Document Model.bulkWrite() API When working with MongoDB and Mongoose in Node.js, handling multiple database operations one by one can be slow and inefficient. Thatâs where the Model.bulkWrite() method comes in handy. This powerful API lets you execute multiple write operations (insert, update, delete, replace) in a single comman
4 min read
Mongoose Document Model.count() API The Model.count() method of the Mongoose API is used to count the number of documents present in the collection based on the given filter condition. It returns the query object and count of documents present in the collection.Syntax:Model.count()Parameters: The Model.count() method accepts two param
2 min read
Mongoose Document Model.countDocuments() API The Model.countDocuments() method of the Mongoose API is used to count the number of document present in a collection. The countDocument() method count the number of documents in a collection based on matching filter. Model.countDocuments() method accepts four parameters: filter:Â It is an object to
3 min read
Mongoose Model.create() API In Node.js applications, Mongoose provides an effective way to interact with MongoDB, allowing developers to define models and schemas to store and retrieve data. One of the essential methods provided by Mongoose is Model.create(), which is used to create one or more documents in a MongoDB collectio
5 min read
Mongoose Document Model.deleteMany() API The Model.deleteMany() method of the Mongoose API is used to delete more than one document in the collection at a time in one go. We can provide an object which contains a condition to the deleteMany() and can be executed on the model object. It will delete all the documents from the collection that
3 min read
Mongoose Document Model.deleteOne() API The Model.deleteOne() method of the Mongoose API is used to delete a document from the collection. We can provide an object of the field to the deleteOne() and can be executed on the model object. It will delete the first document that matches the condition from the collection. Syntax: Model.deleteO
3 min read
Mongoose Document Model.estimatedDocumentCount() API The Model.estimatedDocumentCount() method of the Mongoose API is used to count the number of documents in the MongoDB collection. It is useful for large collections. It is faster than other methods provided by mongoose because it collects metadata instead of scanning the entire collection.Syntax:Mod
2 min read
Mongoose Document Model.events API The Model.events property of Mongoose API is used to return the model's events instance. The instance of the event contains the fields like _events, _eventsCount, and _maxListeners. Syntax: Model_Name.events Return Value: The Model.events property returns the events instance of the model. Setting up
3 min read
Understanding Mongoose Model.exists() API for Efficient Document Search Mongoose, a well-known Object Data Modeling (ODM) library for MongoDB and Node.js. It gives a convenient method of dealing with MongoDB data. One of its critical APIs is the Model.exists() API that facilitates the efficient identification of whether a document exists in a collection by certain condi
4 min read