Working with databases from Node is easy. But then working with a support from ORM/ODM makes it more interesting. Last time we saw how we can work with SQL servers?
, this post is about NoSQL servers, specifically MongoDB. There is a nice ODM for MongoDB known as mongoose.
This mongoose makes the database calls as simple as it could be. The concepts here are
- Define a schema
- Get the Model from the Schema
- Do the database operations on the Model
The sample project is here in Github
.
The first call to mongoose is a connection to MongoDB.
var mongoose = require('mongoose');
mongoose.connect( mongoURL , {useUnifiedTopology: true,useNewUrlParser: true},function(error){
if(error){
throw error
}
console.log('Connection : SUCCESS : ');
// Go ahead with Database modifications
//
});
There are two ways to call connect
function. The way it is shown above will give error
object if there is an error in connection. One has to check for the availability of this object and do things accordingly. If not present, then we have a successful connection. Once that is done, one can call the CRUD methods of the model for modifying the database.
A model file(example: dog.model.js
) will look as below.
const mongoose = require('mongoose');
const DogSchema = mongoose.Schema({
name: String,
description: String
});
const DogModel = mongoose.model('MyDog', DogSchema);
module.exports = DogModel;
This is how to get the model and from there on, you can use the mongoose API to modify the database through the model Object.
Happy Coding.