In Mongoose, a Schema acts as your blueprint and defines what each document in MongoDB should look like including fields, types, defaults and rules. A Model acts as your builder and allows you to create, read, update and delete documents in the database with ease.
Steps to Create Model with Mongoose Schema
To demonstrate how to create a model using Mongoose, follow these steps to set up the environment:
Step 1: Initialize a Node.js Project
First, we need to create a Node.js project if you haven't done so already. Run the following command in your terminal:
npm init -yThis will generate a package.json file, which will manage the project's dependencies.
"start": "node app.js" We can start the developement server using the below command.
npm startNote: The above command will not do anything right now since we have not written any code in our JavaScript file.
Step 2: Install Mongoose and MongoDB Dependencies
We need to install the required modules to use in our project. Run the following command to install MongoDB and Mongoose as dependencies.
npm install mongodb mongooseStep 3: Create the app.js File
Now, create an app.js file where you will define the Mongoose schema and model and connect to MongoDB. Start by connecting to your MongoDB instance:
// app.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/magesDB', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.log('Could not connect to MongoDB...', err));
Step 4: Define the Mongoose Schema
To create a schema and model in Mongoose, define a schema with fields like name, power type, gold, health, and mana for a "Mage." Use mongoose.Schema() to set up the structure, ensuring required fields. Then, use mongoose.model() to create a model based on this schema, enabling interaction with the database.
// Filename - app.js
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
})
Step 5: Create the Model Using the Schema
Once the schema is defined, create a model using mongoose.model(). This model will provide an interface to interact with the mages collection in the MongoDB database.
const Mage = mongoose.model('Mage', mageSchema);Step 6: Create and Save Documents Using the Model
To create and save a model in Mongoose, instantiate an object from the model class using the new keyword, then call the save() method on this object to create a document in the corresponding MongoDB collection.
// app.js
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();
We 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.
We 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.
// app.js
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();
Re-start the server:
npm startOutput: