Mongoose - Creating an Application
January 25th 2021 63

So lets create a project folder “node-mongoose
” and inside your project folder create a folder called models
and inside that create a file called todos.js
and paste below code into it and your todos.js
model file should look like this:
// models/todos.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const todoSchema = new Schema(
{
description: {
type: String,
required: [true, "please enter task details"],
},
completed: {
type: Boolean,
default: false,
},
},
{
timestamps: true,
}
);
var Todos = mongoose.model("Todo", todoSchema);
module.exports = Todos;
In previous section we had implemented this model, if you haven't followed that checkout this, then you are good to continue this section.
Folder Structure:
node-mongoose
- models
- todos.js
Now, open a terminal in node-mongoose
i.e root folder of your project and follow below steps:-
npm init -y
- Create a file called
app.js
- Install express using
npm install express
- Install mongoose using
npm install mongoose
- Install dotenv using
npm install dotenv
- Create a file called
app.js
in root folder of your project - Now follow the steps in this blog and get the
database url
which will look like this :- mongodb+srv://sample_user:<password>@my-sample-cluster-b3ugy.mongodb.net/<dbname>?retryWrites=true&w=majority
- Create a
.env
file in the root folder - Add this line in the .env file with your password and database name
DATABASE_URL=mongodb+srv://sample_user:<password>@my-sample-cluster-b3ugy.mongodb.net/<dbname>?retryWrites=true&w=majority
- Also to ensure your database connection should not visible to other if you are storing your code on a service like Github. Create a
.gitignore
file and enter the file name.env
inside it. So git will not keep track of this file. - Also add one more variable on new line inside
.env
file calledPORT=3000
Your .env
file should look like:
DATABASE_URL=mongodb+srv://sample_user:<password>@my-sample-cluster-b3ugy.mongodb.net/<dbname>?retryWrites=true&w=majority
PORT=3000
Your .gitignore
file should look like
node_modules
.env
Now, lets import the packages we have install into the app.js
file
const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
Now, lets load the environment variable
dotenv.config({ path: ".env" });
const PORT = process.env.PORT;
const dbURI = process.env.DATABASE_URL;
Now lets import the model todos
we have created inside the models/
folder
//model
const Tasks = require("./models/todos");
now , lets create a database connection
:
const connect = mongoose.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
connect.then(
(db) => {
console.log("Connected Successfully to Mongodb Server");
},
(err) => {
console.log(err);
}
);
Lets initialize the express app
:
const app = express();
Lets add a middleware
which converts the request body into json:
app.use(express.json());
Finally lets create a listener to accept incoming HTTP request on specific port:
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
Your Final app.js
should look like this:
const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config({ path: ".env" });
const PORT = process.env.PORT;
const dbURI = process.env.DATABASE_URL;
//model
const Tasks = require("./models/todos");
const connect = mongoose.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
connect.then(
(db) => {
console.log("Connected Successfully to Mongodb Server");
},
(err) => {
console.log(err);
}
);
const app = express();
app.use(express.json());
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
Now we are good to go with basic CRUD
operations.