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])

var mongoose=require('mongoose');
var Schema = mongoose.Schema;
var con ;
var userSchema= new Schema({
  userid: {type:String, required:true, trim:true,index:true,unique:true},
  chips: {type:Number}
});

var userModel = mongoose.model('users',userSchema);
var alex = new userModel({userid:'Alex',chips:10000,regdate:Date.now});
var cb = function(err){
  if(!err)
    console.log("Connection Opened");
  else
    console.log("Connection Opened Failed");
  };
mongoose.connect("mongodb://localhost/tutorialtous",cb);
con = mongoose.connection;
alex.save(function(err,alex){
  if(err){
    console.log(err);
  }else{
    console.log("Document Save Done");
  }

});

>_ 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:-

var mongoose=require('mongoose');
var Schema = mongoose.Schema;
var con ;
var userSchema= new Schema({
  userid: {type:String, required:true, trim:true,index:true,unique:true},
  chips: {type:Number}
});

var userModel = mongoose.model('users',userSchema);
var alex = new userModel({userid:'Alex',chips:10000,regdate:Date.now});
var mark = new userModel({userid:'Mark',chips:15000,regdate:Date.now});

var cb = function(err){
  if(!err){
    console.log("connection opened \t"+con.readyState);
  }else{
    console.log(err);
  }
};

mongoose.connect("mongodb://localhost/tutorialtous",cb);
con = mongoose.connection;
 
var echoRecords =function(err,log){
  console.log("Total Records Found:"+log.length);
  for(var i=0;i<log.length;i++){
    console.log((i+1)+"\t"+log[i]._id+"\t"+log[i].userid+"\t"+log[i].chips);
  }
};

var saveResponse =function(err){
  if(err){
  console.log("save Failed");
  }else{
  console.log("save success");
  }
};

alex.save(saveResponse);
mark.save(saveResponse);

userModel.find(echoRecords);
userModel.find({userid:"Alex"},echoRecords);
userModel.find({userid:"Alex"},{_id:0},echoRecords);

>_ update()

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

userModel.update({userid:"Alex"},{chips:25000},function(err,log){
console.log("Number of Records Effected"+log);
});

userModel.update({chips:{$lt:20000}},{chips:35000},{multi:true},function(err,log){
console.log("Number of Records Effected"+log);
});

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"

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

2. Remove all documents of users collection

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"

userModel.findOne({_id:"57971362517cdfd0260a638c"},"chips,userid",
  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"

userModel.findOneAndRemove({_id:"57971362517cdfd0260a638c"},
  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"

userModel.findByIdAndRemove("5797137d0856a7c41299e099",
{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"

userModel.findById("57971362517cdfd0260a638c","chips,userid",
  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"

userModel.findByIdAndRemove("57971362517cdfd0260a638c",
  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"

userModel.findByIdAndRemove("5797137d0856a7c41299e099",
  {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

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

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

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

>_ where()

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

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

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

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

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

Complete Example:-

var mongoose=require('mongoose');
var Schema = mongoose.Schema;
var con = mongoose.createConnection();
var userSchema= new Schema({
  trim:true,index:true,unique:true},
});
var userModel = mongoose.model('users',userSchema);
  userid: {type:String, required:true,
  chips: {type:Number}
var echo=function(err,log){
  if(!err){
  console.log(log);
  }
}
mongoose.connect("mongodb://localhost/tutorialtous",cb);
con = mongoose.connection;
userModel.where('chips').lt(10000)
  .where('country').eq('USA').exec(echo);

Copyright © 2018-2020 TutorialToUs. All rights reserved.