Backend
CHAI AUR CODE
ODM Mongoose
Getting Started

Getting Started with Mongoose

Introduction

The first step to create a model folder in the root of the directory.

The standard structure of the model folder is as follows:

    • user.models.js
    • todo.models.js
  • This is the common structure of the model folder. It is the standard practice to name the file as filename.models.js.

    💡
    Use either model.js or models.js as the file name.

    Basics of Mongoose

    Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks.

    Mongoose helps us to create schemas and models for MongoDB collections.

    Import Mongoose

    import mongoose from "mongoose";

    Create a Schema

    const userSchema = new mongoose.Schema({});

    With the above code, we have created a schema for the user.

    Export the Model

    export default mongoose.model("User", userSchema);

    Why do we need to export the model ❓

    We need to export the model to use it in other files.

    Mongoose Schema Example

    import mongoose from "mongoose";
     
    const userSchema = new mongoose.Schema({
      // Define the schema here
    });
     
    export default mongoose.model("User", userSchema);

    Interview Question

    How will the model be stored in the database?

    The model will be stored in the database as users. Mongoose automatically pluralizes the model nameand lowercases it.

    Conclusion

    In this article, we learned about the basics of Mongoose and how to create a schema and model using Mongoose.