Open In App

Mongoose Schemas Creating a model

Improve
Improve
Like Article
Like
Save
Share
Report

Mongoose is the most popular ODM mapping library for the MongoDB database. In this article, we will see how to use it to build a model for our database, which can be a little hectic when using pure MongoDB for a large and complex application. We will be using Nodejs to demonstrate the use of mongoose.

We are going to need the following pieces of software to see how mongoose is used to create a model in databases using a schema. We will need code editor such as VS Code, Nodejs and A database viewer, for example, Robo 3T, is now named Studio 3T.

Step 1: Open a new folder in VS Code, and create a new file, app.js. Now open the terminal and type in the following command. This command will initialize a node project, creating a package.json file, which holds information about our project and the dependencies used in it. It also has the script commands we define.

npm init -y

Now that we have initialized a node project, we need to add a script command to it. Open the package.json file and under the scripts key, enter a new key, start, and set its value to “node app.js”.  

package.json

Step 2: Whenever a web application built using Nodejs is hosted, the hosting service or other people viewing your code use the command given below to run it, otherwise, they will have to look for the name of your main file and then write a command, especially for it. The start command generalizes the concept of starting the Nodejs application.

npm start

Note: The above command will not do anything right now since we have not written any code in our JavaScript file.

Step 3: Importing library and Connecting to Database. We cannot just start writing code that will allow us to use the Mongoose library to set up and use a MongoDB database. We need to install the required libraries for it from the NPM repository, which is a cloud repository of third-party packages for Nodejs applications. Write the following commands into the terminal to install the mongodb and mongoose libraries.

npm install mongodb mongoose

Now write the following code into the app.js file to import the mongoose library and use its connect method to connect to a MongoDB database. If such a database does not exist, it will be created. The URL shown in the code below is for local DB, with the name of our database at last. You can also add a URL to a cloud MongoDB database. We don’t import and use the mongodb library because it was needed only for the mongoose library to use in the background. Remember that mongoose works for only a MongoDB database.

file: app.js

Javascript




const mongoose = require('mongoose');


Step 4: Deciding a Blueprint for our Model. We are creating a database for holding data of mages hidden all around the world. The mage is going to have a name, a power type, gold, health and mana powers. Thus these are the fields we are going to have for each mage here. In MongoDB, the collection is like a table, and the document is like a row of the table that holds all data representing a single entity. We use the mongoose constant to use all methods provided by the mongoose library. We call the Schema method and pass it a JavaScript object, with the fields mentioned above. Their values are the datatypes that will hold. Since this is just a blueprint, we are not going to give any solid data. We can also pass an object to a key, this object will define additional properties of the field. Here, the only additional property we need is that name and power type key cannot be empty. Thus we put the require key to true. All of this needs to be assigned to a constant as shown below.

To bring this blueprint, i.e., the schema to actuality, we use mongoose.model method. We pass it two arguments, the first is the name of the collection, and the second is the schema. Keep the case of the string exactly as shown. Mongoose will automatically convert it to the small case and singular. Assign it to a constant. Now, this constant is a class from which we can create multiple objects.

File: app.js

Javascript




const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/magesDB");
  
const mageSchema = new mongoose.Schema({
    name: {
        type: String,
        require: true
    },
    power_type: {
        type: String,
        require: true
    },
    mana_power: Number,
    health: Number,
    gold: Number
})
  
const Mage = new mongoose.model("Mage", mageSchema)


Step 5: Creating and Saving a Model. Now that we have a class from which we can create objects, that will serve as documents for the collection that the class represents, we create it and save it using the new keyword and the save() method. Create an object from the Mage class as you would in the conventional OOP approach, using the new keyword which invokes a constructor method. Then call the save() method on this object. This will create a document in the mages collection. Now run the code using the below command.

npm start

File: app.js

Javascript




const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/magesDB");
  
const mageSchema = new mongoose.Schema({
    name: {
        type: String,
        require: true
    },
    power_type: {
        type: String,
        require: true
    },
    mana_power: Number,
    health: Number,
    gold: Number
})
  
const Mage = new mongoose.model("Mage", mageSchema)
  
const mage_1 = new Mage({
    name: "Takashi",
    power_type: 'Element',
    mana_power: 200,
    health: 1000,
    gold: 10000
});
  
mage_1.save();


You can view the saved model and document by opening up the Studio 3T desktop application, clicking on connect, and then going through the following hierarchy and double click on the mode collection name.

 

This is what you will see when you double-click on the collection name. Notice that it has been given an _id field automatically.

 

You can create as many objects from the Mage class as you want, and call the save() method on them to create a document for each of them in the mages collection.

File: app.js

Javascript




const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/magesDB");
  
const mageSchema = new mongoose.Schema({
    name: {
        type: String,
        require: true
    },
    power_type: {
        type: String,
        require: true
    },
    mana_power: Number,
    health: Number,
    gold: Number
})
  
const Mage = new mongoose.model("Mage", mageSchema)
  
const mage_1 = new Mage({
    name: "Takashi",
    power_type: 'Element',
    mana_power: 200,
    health: 1000,
    gold: 10000
});
  
mage_1.save();
  
const mage_2 = new Mage({
    name: "Steve",
    power_type: 'Physical',
    mana_power: "500",
    health: "5000",
    gold: "50"
})
  
mage_2.save();


Output:

 



Last Updated : 29 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads