CRUD operations using Mongoose in NodeJS
Connection to MongoDB
To establish a connection to MongoDB first we need to import mongoose module to our project which is available in the NPM registry.
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/play')
.then(() => console.log('Connected to database'))
.catch(err => console.log('could not connect to the mongo db'));
** Schema **
Once the connection established we need to define a schema. We use schema to define the shape of a document within a collection in MongoDB. Schema is specific to the mongoose.
Let's see how to design a schema
const courseObj = new mongoose.Schema({
name: {
type:String,
required: true,
minlength: 5,
maxlength: 255
},
category:{
type: String,
enum: ['web', 'db', 'Mobile', 'Network']
},
author: String,
tags: {
type: Array
},
date: {type: Date, default: Date.now},
isPublished: Boolean,
})
List of types in Schema
String, Number, Date, Buffer, Boolean, ObjectId, Array
** Model**
Once we create a schema we need to compile that schema into a model. Schema is a class and model is an object to the class.
Let's create a model for the above schema.
const Course = mongoose.model('Course', courseObj);
//mongoose.model method takes two parameters first argument is for collection to which this model is for and another is schemaObject.
** CRUD Operations **
** Create **
Once we create a model then we can create, read, update and delete a document from the database. Let's see how to create a document in the database.
async function createCourseObj(){
const course = new Course({
name: 'Java course',
category: 'db',
author: 'Madhav',
// tags: ['Java', 'Backend'],
isPublished: true,
price: 15
})
try {
const result = await course.save(); //save method is used to store a document
console.log('result',result);
}
catch(err) {
console.log(err)
}
}
** Read **:
Let's see how to query a document
async function getCourses(){
const courses = await Course
//.find({price: {$gte: 10}})
.find()
.or([{author: 'madhav'}, {isPublished:true}])
.limit(5)
.select({name: 1, tags: 1});
console.log(courses);
//find method is used to query a document
}
** Update **:
To update a document
async function updateCourse(id) {
const course = await Course.findByIdAndUpdate(id, {
$set: {
author: 'Krishna',
isPublished: true
}
}, {new: true});
console.log(course);
}
** Delete **:
To remove a document from the database
async function deleteCourse(id) {
const course = await Course.findByIdAndRemove({_id: id});
console.log(course);
}