Connecting To MongoDB Using Mongoose: Node.js

Lets learn to connect to MongoDB server from our Node.js application using Mongoose module.
mongoose Module
Mongoose provides a straight-forward, schema-based solution to modeling your application data and includes built-in type casting, validation, query building, business logic hooks and more..
MongoDB
MongoDB is one of the leading NoSQL database. Know more about it at MongoDB – Getting Started Guide
$ npm install express mongoose --save
Creating the connection
Next we connect to mongobd using connect method of mongoose module. Here we also specify the mongoDB database name to which our application will be connecting to. If the database is not already present, this will create one for us.
Create a file server.js , import all the required dependencies and call mongoose.connect(uri , options , callback) Server.js
const mongoose = require("mongoose"); mongoose.connect("mongodb://localhost/test",
{ useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
}, () => {
console.log("connected");
});
Make sure your mongo is running on localhost on the default port. For atlas your URI will be:
`mongodb+srv://${usrname}:${pass}@${cluster}.mongodb.net/${db_name}?retryWrites=true&w=majority`,
We will be requiring express to create the HTTP server, we won't be using HTTP module by node as it will be another boilerplate. Also, we will be using mongoose to connect our node application with DB
To make sure your connection was successful, add the following code right below your mongoose.connect(). Now at last app.listen() on 3000 port with a success callback.
app.listen(3000, () => { console.log("Server is running"); });
Create the schema & Model
Next, we write a schema definition for our collection. Mongoose uses schema for validation of user entered data. By specifying the data type for our field we can make sure user entries are validated against the data types we have mentioned in our schema.
According to Node JS, best practices use a different folder for all your views, models, routes. Create file user.js and add the following code. user.js
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
name: String,
age: Number,
});
const User = mongoose.model("User", UserSchema);
module.exports = User;
Create Your First Entry
// import user model
// use this code on any post route
const user = new User(request.body); // json body parser
try {
await user.save(); // user.save() is an async call
response.send(user);
} catch (error) {
response.status(500).json({“msg”:”something went wrong”});
}
Conclusion
That’s it — now you know how to connect your Node.js app to MongoDB using Mongoose. We set up the connection, created a schema, and saved data. This is the base of any backend app. From here, you can easily build full CRUD and real projects.




