Home » Create Method in Mongoose

Create Method in Mongoose

Create Method in Mongoose

Introduction

Mongoose is a popular Object Data Modeling (ODM) library for MongoDB and Node.js. It allows developers to define schemas for their data, making it easier to enforce data validation and integrate with MongoDB. One fundamental operation in any database is creating new records. In Mongoose, this is done using the create method, known as the Create Method in Mongoose.

Syntax of Create Method in Mongoose

Model.create(docs, [callback]);
JavaScript

Model: The Mongoose model you are using.
docs: The document(s) you want to create. This can be a single object or an array of objects.
callback: An optional callback function that gets called after the documents are created.

Why Do We Need the Create Method?

  1. Simplified Document Creation: The create method provides a straightforward way to add new documents, eliminating the need for manual validation and insertion.
  2. Schema Validation: When using the create method, Mongoose automatically applies schema validation to ensure that the documents adhere to the defined schema.
  3. Middleware: Any middleware defined for the save operation in your schema will also run when using the create method, ensuring consistent application behavior.
  4. Error Handling: The create method comes with built-in error handling, making it easier to manage and debug issues during document creation.

Examples

First, install Mongoose if you haven’t already.

npm install mongoose
JavaScript

Next, create a Mongoose model for a User

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Define the User schema
const userSchema = new Schema({
  name: String,
  email: { type: String, unique: true },
  age: Number
});

// Create the User model
const User = mongoose.model('User', userSchema);

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log('Connected to MongoDB');
    
    // Use the create method to add a new user
    User.create({ name: 'John Doe', email: 'john@example.com', age: 30 })
      .then(user => {
        console.log('User created:', user);
      })
      .catch(error => {
        console.error('Error creating user:', error);
      });
  })
  .catch(error => {
    console.error('Error connecting to MongoDB:', error);
  });
JavaScript

Output:-

Connected to MongoDB
User created: {
  _id: 60d9f7cbb508b42494c9b5f1,
  name: 'John Doe',
  email: 'john@example.com',
  age: 30,
  __v: 0
}
Bash

If there is an error (for example, a duplicate email), you will see an error message:

Error creating user: MongoError: E11000 duplicate key error collection: mydatabase.users index: email_1 dup key: { : "john@example.com" }
Bash

Conclusion

The create method in Mongoose is a powerful and convenient way to add new documents to your MongoDB collections. It simplifies document creation, ensures schema validation, and integrates with middleware for consistent behavior. By using the create method, you can efficiently manage the insertion of new data into your MongoDB database.

Frequently Asked Questions

1. What happens if one document in the array fails validation when creating multiple documents?

If one document in the array fails validation, none of the documents will be created. Mongoose performs validation for all documents before inserting them into the database.

2. Is it necessary to use a callback with the create method?

No, using a callback is optional. The create method returns a promise, so you can use .then() and .catch() for handling the results and errors, which is the preferred approach in modern JavaScript.

3. Can I use the create method with pre-save middleware?

Yes, any middleware defined for the save operation in your schema will also run when using the create method. This ensures that any logic you have in your middleware is applied consistently.