Debug School

rakesh kumar
rakesh kumar

Posted on

Creating schema in node js

In Node.js and MongoDB, a schema is a way to define the structure, data types, and constraints for the documents stored in a MongoDB collection. Schemas are commonly used with libraries like Mongoose, which provides an object modeling interface for MongoDB in Node.js.

Here's an example of how you can define a schema using Mongoose:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: String,
  age: Number,
  email: {
    type: String,
    required: true,
    unique: true
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

const User = mongoose.model('User', userSchema);
Enter fullscreen mode Exit fullscreen mode

In the above example, we define a schema for a user collection. The schema specifies four fields: name, age, email, and createdAt. Let's break down the schema definition:

The name field is defined as a String data type. By specifying only the data type, we indicate that the field is optional and can have any value.

The age field is defined as a Number data type. Similar to the name field, it's optional and can have any numeric value.

The email field is defined as a String data type and has additional properties. We've set required: true, which means the field must be present when inserting or updating a document. Additionally, unique: true ensures that each user document has a unique email address.

The createdAt field is defined as a Date data type. We've specified a default value of Date.now, so if this field is not provided during document creation, it will automatically be set to the current date and time.

After defining the schema, we create a model using mongoose.model(). The model represents a MongoDB collection and allows us to perform CRUD (Create, Read, Update, Delete) operations on the collection.

Using a schema provides several benefits:

  1. It enforces consistency in the structure of the documents stored in the collection.
  2. It allows you to define data types for each field, ensuring that the data is stored in the appropriate format.
  3. It enables the use of built-in and custom validators to enforce constraints and validate the data before saving it to the database.
  4. It provides default values for fields, simplifying document creation . Schemas help in organizing and defining the structure of data stored in a MongoDB collection, ensuring data integrity and making it easier to work with the database in a structured manner.

=================================================================
step1:create schema.js

Image description

step 2:create modal

Image description

step 3:create controller
Image description
step 4:create route

Image description

Run Schema

Image description

Image description

Top comments (0)