First of all, it is important to establish a connection with the MongoDB database through Mongoose. Mongoose makes this quite easy. You can use the following snippet to easily connect to a local database.

In NodeJS, whenever we call requires, the process is paused until the file is imported. Once mongoose is imported, we use its connect method and pass in three arguments:

  • URL for the database
  • Options for Configuring Mongoose
  • Callback function to catch errors

Mongoose Schema and Data Types

A schema isn’t something that MongoDB is famous for. It is a NoSQL data database and does not require a strict schema to save documents (data.) Still, most users prefer saving data according to a pre-defined schema because it helps with scalability. A mongoose schema not only keeps documents in a specified format but also helps with validation.
The Mongoose Schema supports various data types including, but not limited to:

  • String
  • Number
  • Date
  • Array
  • Boolean
  • Mixed
  • Buffer

All of these data types have their advantages and disadvantages. I assume that most of you already know JS and are familiar with most of these data types. If you want a complete explanation of these JS data types then please leave comments regarding the same below.
To create a schema, type in the following code:

Once you have created the schema, you need to register the Model.

mongoose.model takes two parameters,

  • Model Name: the name of the model is stored as lowercase and plural form in the MongoDB database
  • Schema Function: The schema function created for the model

After registering the Schema, we’re ready to save documents to the database with mongoose.

CRUD (Create, Read, Update and Delete)

Crud operations are great and can be very nice when taken seriously!


Weird Programmer

I hate people who use LOL in face to face conversations. Also, if I tell you anything else about myself, then I'll have to KILL you~~!

Leave a Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of
%d bloggers like this: