Using MongoDB on Node.js Application Using Mongoose
In this post, we are going to see how we can use a MongoDB database with our Node.js application with the help of the package Mongoose.
Join the DZone community and get the full member experience.
Join For Free
introduction
in this post, we are going to see how we can use mongodb in our node.js application with the help of the package mongoose. we will also be covering some facts about mongodb so that, as a reader, you will understand why we have chosen mongodb as our backend. we will be going through some steps to install the required packages using a node package manager terminal, so please bear with me. at the end of this article, i guarantee that you will be proficient on how to connect a mongodb database to your node application. i hope you will like this article.
why mongodb?
here, i am going to list the reasons why i chose mongodb.
- mongodb is a nosql database - when i say nosql, it means that it doesn't have any structure to be followed.
- there are no relationships, we can perform the relation using separate packages like mongoose.
- everything is json, even the data and collections are stored as json.
- since the data is stored as json, no more conversions are needed. we can directly use it in our application.
you can always clone or download the source code here .
background
node.js has become a trend now. one of the recommended databases for a node application is mongodb. as we discussed, a mongodb database doesn't have any structure built-in, here we are going to use a package called mongoose, with that we can create some structure for our database. let's just skip the talking and start developing.
setting up a node application
to get started with node.js, create a folder and name it; this is going to be our project directory. here, i am going to use one of my favorite editors, visual studio code. now please point to your project container, and run the below command.
npm init
this will create a file named "package.json" in your directory. we will be adding all of our dependencies in this file very soon. the command may ask you some default questions which you need to answer. if you need to create the package.json file with default values in it, you may consider running the below command.
npm init --yes
let's review our package.json file.
{
"name": "node-mongodb-mongoose",
"version": "1.0.0",
"description": "a node application with mongodb and mongoose",
"main": "index.js",
"scripts": {
"test": "echo \"error: no test specified\" && exit 1"
},
"keywords": [
"node",
"mongoose",
"mongodb"
],
"author": "sibeesh venu",
"license": "isc"
}
getting the required packages
now that we have the application ready, let's get the required packages ready.
npm install --save mongoose
this will create a new folder, npm_modules, on your project directory where you can see the package mongoose in it.
npm install --save express
the above command will add the package express to our application.
creating the node app
now we can create our server.js file where we are going to write most of our application code.
var express = require("express")
var app = express()
app.listen("3010",()=>{
console.log("i just started listening!.")
})
now run the command
node server.js
and make sure that you are getting the message, "i just started listening!"
if you are getting the following error, please make sure that you are running the application on an unused port.
ps f:\visual studio\node.js\node-mongodb-mongoose> node server.js
events.js:136
throw er; // unhandled 'error' event
^error: listen eaddrinuse :::3000
at object._errnoexception (util.js:1031:13)
at _exceptionwithhostport (util.js:1052:20)
at server.setuplistenhandle [as _listen2] (net.js:1367:14)
at listenincluster (net.js:1408:12)
at server.listen (net.js:1496:7)
at function.listen (f:\visual studio\node.js\node-mongodb-mongoose\node_modules\express\lib\application.js:618:24)
at object.<anonymous> (f:\visual studio\node.js\node-mongodb-mongoose\server.js:3:5)
at module._compile (module.js:641:30)
at object.module._extensions..js (module.js:652:10)
at module.load (module.js:560:32)"
setting up the database
now that we have our application ready, let's go and create our database. i am going to use mlab for creating the database. if you have not installed mongodb on your machine, i strongly recommend creating a database in mlab. i had created a database there and have got my connection string as follows.
mongodb://<dbuser>:<dbpassword>@ds038319.mlab.com:38319/mylearning
we will be updating the connection string with an actual db user and password later. please make sure that you are creating a user for your db and remember the password.
creating a mongoose model
let's create a mongoose model and set up our connection string now, which is going to be our collection. no worries, it is just a javascript model.
var constring = "mongodb://admin:admin@ds038319.mlab.com:38319/mylearning"
/**
* models
*/
var user = mongoose.model("user", {
firstname: string,
lastname: string
})
please note that when you move the code to production, make sure that your password and user fields on the connection string are separated from this file and encrypted.
now let's connect our database.
mongoose.connect(constring, { usemongoclient: true }, () => {
console.log("db is connected")
})
setup the data
we have our model ready, what else is needed now? yes, you are right, we need data.
var dummyuser = {
firstname: "sibeesh",
lastname: "venu"
}
inserting the data into mongodb
we have got everything ready, so we can insert the model now. let's do the saving logic first.
mongoose.connect(constring, { usemongoclient: true }, () => {
console.log("db is connected")
savedata()
})
function savedata() {
var user = new user(dummyuser);
user.save();
}
verify the data
once you run your application, go to your database and check for the entries there. i am sure there will be a new collection ("user") and our inserted data. as i am using a mlab database, here is how my data saved.
if you have noticed, you can see there is another property names "_id" in our database collection. this is a unique id generated by mongodb for us, so no need to think about it.
as the purpose of this article is to show how we can insert a data to mongodb, i called the save method right after the database was connected. in real life, this is not a recommended method. you must create an ajax post request and handle the event. i am leaving that task to you. please try to do that and let me know. i would love to hear back from you.
conclusion
thanks a lot for reading. did i miss anything that you think is needed? did you find this post useful? i hope you liked this article. please share with me your valuable suggestions and feedback.
kindest regards
sibeesh venu
Published at DZone with permission of Sibeesh Venu, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments