10. Mongoose CRUD Operations

Objectives :In the this section, we’re going to Learn how to perform crud operations in Mongoose .

Key Terms

  • Save
  • find
  • update
  • remove

Mongoose CRUD Operations

create, read, update and delete (as an acronym CRUD) are the four basic functions of persistent storage. Using some methods of Mongoose we will implement CRUD operations.

Lets view the methods for CRUD operations

>_ Constructor Model()

Model constructor

Syntax:
Model(doc)

>_ save()

Saves the document.

Syntax:- save([options], [options.safe], [options.validateBeforeSave], [fn])

01 var mongoose=require('mongoose');
02 var Schema = mongoose.Schema;
03 var con ;
04 var userSchema= new Schema({
05   userid: {type:String, required:true, trim:true,index:true,unique:true},
06   chips: {type:Number}
07 });
08
09 var userModel = mongoose.model('users',userSchema);
10 var alex = new userModel({userid:'Alex',chips:10000,regdate:Date.now});
11 var cb = function(err){
12   if(!err)
13     console.log("Connection Opened");
14   else
15     console.log("Connection Opened Failed");
16   };
17 mongoose.connect("mongodb://localhost/tutorialtous",cb);
18 con = mongoose.connection;
19 alex.save(function(err,alex){
20   if(err){
21     console.log(err);
22   }else{
23     console.log("Document Save Done");
24   }
25
26 });

>_ find()

Find the documents of a collection/model.
Note:-
We need to call find() methods with Model Instances unlike save(), means like userModel.find() is valid.

Syntax:- find(conditions, [projection], [options], [callback])

Conditions, projection, options are similar to mongodb’s find() method.
Example:-

01 var mongoose=require('mongoose');
02 var Schema = mongoose.Schema;
03 var con ;
04 var userSchema= new Schema({
05   userid: {type:String, required:true, trim:true,index:true,unique:true},
06   chips: {type:Number}
07 });
08
09 var userModel = mongoose.model('users',userSchema);
10 var alex = new userModel({userid:'Alex',chips:10000,regdate:Date.now});
11 var mark = new userModel({userid:'Mark',chips:15000,regdate:Date.now});
12
13 var cb = function(err){
14   if(!err){
15     console.log("connection opened \t"+con.readyState);
16   }else{
17     console.log(err);
18   }
19 };
20
21 mongoose.connect("mongodb://localhost/tutorialtous",cb);
22 con = mongoose.connection;
23  
24 var echoRecords =function(err,log){
25   console.log("Total Records Found:"+log.length);
26   for(var i=0;i<log.length;i++){
27     console.log((i+1)+"\t"+log[i]._id+"\t"+log[i].userid+"\t"+log[i].chips);
28   }
29 };
30
31 var saveResponse =function(err){
32   if(err){
33   console.log("save Failed");
34   }else{
35   console.log("save success");
36   }
37 };
38
39 alex.save(saveResponse);
40 mark.save(saveResponse);
41
42 userModel.find(echoRecords);
43 userModel.find({userid:"Alex"},echoRecords);
44 userModel.find({userid:"Alex"},{_id:0},echoRecords);

 

>_ update()

Updates documents in the database without returning them.
Syntax:-
update(conditions, doc, [options], [callback])
Example:-

1 userModel.update({userid:"Alex"},{chips:25000},function(err,log){
2 console.log("Number of Records Effected"+log);
3 });
4
5 userModel.update({chips:{$lt:20000}},{chips:35000},{multi:true},function(err,log){
6 console.log("Number of Records Effected"+log);
7 });

It will returns number of documents updated count

 

>_ remove()

Removes document/s from the collection.

Syntax:-
remove(conditions, [callback])
Note:-
1. If condition not passed or empty then all the records will be removed.

Example:-
1. Remove the document having userid “Alex”

1 userModel.remove({userid:"Alex"})

2. Remove all documents of users collection

1 userModel.remove()

 

>_ findOne()

Finds a single document by its _id field.

Syntax:-
findOne([conditions], [projection], [options], [callback])
Example:-
1.Find the user details having the id “57971362517cdfd0260a638c”

1 userModel.findOne({_id:"57971362517cdfd0260a638c"},"chips,userid",
2   function(err,data){if(!err) console.log(data);});

 

>_ findOneAndRemove()

Issue a mongodb findAndModify remove command.

Syntax:-
findOneAndRemove(conditions, [options], [callback])
Example:-
1. Remove the user details having the id “57971362517cdfd0260a638c”

1 userModel.findOneAndRemove({_id:"57971362517cdfd0260a638c"},
2   function(err,data){if(!err) console.log(data);});

 

>_ findByIdAndUpdate()

Finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. The query executes immediately if callback is passed else a Query object is returned.

Syntax:-
findByIdAndUpdate(id, [update], [options], [callback])
Example:-
1. Reset the chips for the id “5797137d0856a7c41299e099”

1 userModel.findByIdAndRemove("5797137d0856a7c41299e099",
2 {chips:0},function(err,data){if(!err) console.log(data);});

 

>_ findById()

Finds a single document by its _id field. findById(id).

Syntax:-
findById(id, [projection], [options], [callback]) Example:-
1.Find the user details having the id “57971362517cdfd0260a638c”

1 userModel.findById("57971362517cdfd0260a638c","chips,userid",
2   function(err,data){if(!err) console.log(data);});

 

>_ findByIdAndRemove()

Issue a mongodb findAndModify remove command by a document’s _id field. findByIdAndRemove(id, …) is equivalent to findOneAndRemove({ _id: id }, …).

Syntax:-
findByIdAndRemove(id, [options], [callback])
Example:-
1. Remove the user details having the id “57971362517cdfd0260a638c”

1 userModel.findByIdAndRemove("57971362517cdfd0260a638c",
2   function(err,data){if(!err) console.log(data);});

 

>_ findByIdAndUpdate()

Finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. The query executes immediately if callback is passed else a Query object is returned.

Syntax:-
findByIdAndUpdate(id, [update], [options], [callback])
Example:-
1. Reset the chips for the id “5797137d0856a7c41299e099”

1 userModel.findByIdAndRemove("5797137d0856a7c41299e099",
2   {chips:0},function(err,data){if(!err) console.log(data);});

 

>_ count()

Counts number of matching documents in a database collection.

Syntax:-
count(conditions, [callback])
Example:-
1. Find Number of Documents in users Schema

1 userModel.count({},function(err,count){
2   console.log("No Of Records in users Schema:"+count);
3 });

 

2. Find Number of Documents in users Schema having chips<=25000

1 userModel.count({chips:{$lte:25000}},function(err,count){
2   console.log("chips <=25000 :"+count);
3 });

 

>_ where()

Creates a Query, applies the passed conditions, and returns the Query.

Syntax:-
where(path, [val])
Example:-
1. Find the users having chips <10000

1 userModel.where('chips').lt(10000);

2. Find the users having chips <10000 of Country ‘USA’

1 userModel.where('chips').lt(10000).where('country').eq('USA');

Complete Example:-

01 var mongoose=require('mongoose');
02 var Schema = mongoose.Schema;
03 var con = mongoose.createConnection();
04 var userSchema= new Schema({
05   trim:true,index:true,unique:true},
06 });
07 var userModel = mongoose.model('users',userSchema);
08   userid: {type:String, required:true,
09   chips: {type:Number}
10 var echo=function(err,log){
11   if(!err){
12   console.log(log);
13   }
14 }
15 mongoose.connect("mongodb://localhost/tutorialtous",cb);
16 con = mongoose.connection;
17 userModel.where('chips').lt(10000)
18   .where('country').eq('USA').exec(echo);