How to setup up Schema for MongoDB using mongoose

How to setup up Schema for MongoDB using mongoose. In this tutorial, we are going to learn about the schema, how to set up a schema in the MERN application, and how the database can handle them.

To understand Schema we will create a small database for dogs and will also make a dog schema that would take the name, age, and breed of the dog.

What is Schema?

The database schema of a database is its structure described in a simple language supported by the database management system. The term “Schema” refers to the organization of data as a blueprint of how the database is constructed. The formal definition of a database schema is a set of formulas called integrity constraints imposed on a database.

⇒ MongoDB saved the information/data in the form of javaScript Object Notation(json) document.As it a non relational database.

⇒ Data is saved in a pattern format and this pattern is set by creating a model of the format of data.

⇒ These models are a very important part of MVC workflow. They are created using the schema function of mongoose.

⇒ This is like a bridge between the database and the web app.

This Small project of dogs will explain how to create schemas and use them.

Steps:-

  1. Create a folder and initialize the project using npm init.
  2. Create an app.js file and install mongoose using the below command.
    PS D:\work\Codebun\Project\dogs>npm i mongoose
  3. Require the mongoose in app.js
  4. Connect to the database using mongoose.connect
  5. Use the Mongoose.Schema() function to specify the model and then use it to save data.
  6. Create an object of that model filling the information and use the mongoose function to save the data to the database.
  7. Use the mongoose.find() function.

Setup up Schema for MongoDB using mongoose

const mongoose = require("mongoose");
//connecting to database
mongoose.connect("mongodb://localhost:27017/Dogs",{
    useNewUrlParser:true,
    useUnifiedTopology:true,
    useCreateIndex:true
})
.then(() => {
    console.log("DB CONNECTED");
  });
//Schema
var dogSchema = new mongoose.Schema({
    name: String,
    age: Number,
    breed:String
})
 
var Dog = mongoose.model("Dog",dogSchema);
//Create
Dog.create({
    name: "wolfy",
    age: 7,
    breed: "Husky"
 }, function(err, dog){
     if(err){
         console.log(err);
     } else {
         console.log("Successfully saved"
);
     }
 });
//Show Collections
 Dog.find({},(err, dog)=>{
     if(err){
         console.log("Not Worked");
         console.log(err);
     }else{
         console.log("All dogs in DB are");
         console.log(dog);
     }
 })

⇒ Run the code using the command node app.js

PS D:\work\Codebun\Project\dogs>node app.js

OUTPUT

Note op is in command prompt/terminal

Note: The _id is created automatically and is unique for each object.