Posts

Showing posts from February, 2025

Creating our model

 CHAT.JS it is exported to index.js const mongoose = require ( "mongoose" ); const chatSchema = new mongoose . Schema ({   from : {     type : String ,     required : true ,   },   to : {     type : String ,     required : true ,   },   msg : {     type : String ,     maxLength : 50 ,   },   created_at : {     type : Date ,     required : true ,   }, }); const Chat = mongoose . model ( "Chat" , chatSchema ); module . exports = Chat ; index.js const Chat = require ( "./models/chat.js" ); let chat1 = new Chat ({   from : "abhi" ,   to : "ash" ,   msg : "silencer" ,   created_at : new Date (), }); chat1   . save ()   . then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err );   });

MongoDB with Express (BASIC SETUP)

 BASIC SETUP const express = require ( "express" ); const app = express (); const mongoose = require ( "mongoose" ); const path = require ( "path" ); app . set ( "views" , path . join ( __ dirname , "views" )); app . set ( "view engine" , "ejs" ); main ()   . then (() => {     console . log ( "connection successful" );   })   . catch (( err ) => {     console . log ( err );   }); async function main () {   await mongoose . connect ( "mongodb://127.0.0.1:27017/whatsapp" ); } app . get ( "/" , ( req , res ) => {   res . send ( "server working" ); }); app . listen ( 8080 , () => {   console . log ( `listening to port` ); });

Validation in Update and errors

Image
RULES DEFINED ARE VALIDATED ONLY DURING INSERTION. WHILE UPDATING THEY ARE NOT VALIDATED price : {     type : Number ,     min : 1 ,   }   Book . findByIdAndUpdate ( "67c1fd5b36e4d6da65845b82" , { price : - 100 })   . then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err );   }); TO OVERCOME THIS  Book . findByIdAndUpdate ( "67c1fd5b36e4d6da65845b82" , { price : - 100 },{ runValidators : true })   . then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err );   }); WE CAN DEFINE CUSTOM ERRORS print the errors that we define   price : {     type : Number ,     min : [ 1 , "Price is too low to afford the book" ],   },

Schema type options

Image
let book2 = new Book ({   title : "Marvel Comics" ,   author : "stan lee" ,   price : 499 ,   category : "comics" , })   . save ()   . then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err );   }); NOW THE CONDITIONS:   title : {     type : String ,     required : true ,     maxlength : 5 ,   },   discount : {     type : Number ,     default : 0 ,   }, HERE WE DIDN'T DEFINE DISCOUNT ,BUT IN THE OUTPUT WE CAN SEE IT, AS IT IS DEFAULT category : {     type : String ,     enum : [ "fiction" , "non-fiction" ],   }, THERE ARE MANY MORE SCHEMA TYPES ,REFER:https://mongoosejs.com/docs/schematypes.html  

Schema Validations

Image
SCHEMA VALIDATION:RULES FOR SCHEMA   const mongoose = require ( "mongoose" ); main ()   . then (() => {     console . log ( "connection successful" );   })   . catch (( err ) => {     console . log ( err );   }); async function main () {   await mongoose . connect ( "mongodb://127.0.0.1:27017/amazon" ); } const bookSchema = new mongoose . Schema ({   title : {     type : String ,     required : true ,   },   author : {     type : String ,   },   price : {     type : Number ,   }, }); const Book = mongoose . model ( "Book" , bookSchema ); let book1 = new Book ({ HERE TITLE NOT DEFINED   author : "r.r.martin" ,   price : 344 , })   . save ()   . then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err );   }); HERE PRICE IS DEFINED A...

DELETE

Image
  // DELETE // DELETEONE User . deleteOne ({ name : "adam" }). then (( res ) => {     console . log ( res ); }) . catch (( err ) => {     console . log ( err ); }) // DELETE MANY User . deleteMany ({ age : 20 }). then (( res ) => {     console . log ( res ); }) . catch (( err ) => {     console . log ( err ); }) // FindOneAndDelete User . findOneAndDelete ({ name : "bruce" })   . then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err );   }); // FindByIdAndDelete User . findByIdAndDelete ( "67c1579265226d7cb73e3d72" ). then (( res ) => {     console . log ( res ); }) . catch (( err ) => {     console . log ( err ); })

FIND AND UPDATE

Image
  User . findOneAndUpdate ({ name : "bruce" }, { age : 35 } )   . then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err );   }); BY USING OPTIONS WE GET THE UPDATED DOCUMENT User . findOneAndUpdate ({ name : "bruce" }, { age : 35 },{ new : true })   . then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err );   }); findById User . findByIdAndUpdate (   "67c1579265226d7cb73e3d72" ,   { name : "gwen tennison" } ,{ new : true } )   . then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err );   });

UPDATE

Image
// //UPDATE User . updateOne ({ age : 21 , name : "bruce" })   . then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err );   }); User . updateMany ({ age : { $gt : 20 } }, { age : 25 })   . then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err );   });

FIND

Image
  //FIND User . find ()   . then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err );   }); User . find ()   . then (( res ) => {     console . log ( res [ 0 ]. name );   })   . catch (( err ) => {     console . log ( err );   }); User . find ({ age : { $gt : 50 }})   . then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err );   }); Model.findOne() User . findOne ({ age : { $gt : 20 }})   . then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err );   }); Model.findById() User . findById ( "67c1579265226d7cb73e3d72" )   . then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err ); ...

INSERT MANY

Image
  const mongoose = require ( "mongoose" ); main ()   . then (() => {     console . log ( "connection successful" );   })   . catch (( err ) => {     console . log ( err );   }); async function main () {   await mongoose . connect ( "mongodb://127.0.0.1:27017/test" ); } const userSchema = new mongoose . Schema ({   name : String ,   email : String ,   age : Number , }); const User = mongoose . model ( "User" , userSchema ); User . insertMany ([     { name : "peter" , email : "spidey@gmail.com" , age : 20 },     { name : "gwen" , email : "gwen@gmail.com" , age : 21 },     { name : "mary" , email : "Mj@gmail.com" , age : 20 },   ]). then (( res ) => {     console . log ( res );   });

INSERT in Mongoose (insert one)

Image
  const mongoose = require ( "mongoose" ); main ()   . then (() => {     console . log ( "connection successful" );   })   . catch (( err ) => {     console . log ( err );   }); async function main () {   await mongoose . connect ( "mongodb://127.0.0.1:27017/test" ); } const userSchema = new mongoose . Schema ({   name : String ,   email : String ,   age : Number , }); const User = mongoose . model ( "User" , userSchema ); const user1 = new User ({   name : "abhi" ,   email : "abhi@mail.com" ,   age : 21 , }); user1 . save (); const user2 = new User ({   name : "adam" ,   email : "ad@gmail.com" ,   age : 77 , }); user2 . save (). then (( res ) => {     console . log ( res );   })   . catch (( err ) => {     console . log ( err );   });

Schema (MONGOOSE)

Image
  const mongoose = require ( "mongoose" ); main ()   . then (() => {     console . log ( "connection successful" );   })   . catch (( err ) => {     console . log ( err );   }); async function main () {   await mongoose . connect ( "mongodb://127.0.0.1:27017/test" ); } const user = new mongoose . Schema ({   name : String ,   email : String ,   age : Number , });

DELETE

Image
 db.student.deleteOne({city:"gujarat"})  db.student.deleteMany({marks:{$lt:75}}) db.student.deleteMany({}) db.dropDatabase()

nesting

Image
 db.student.insertone({name:"max",performance:{marks:137,grade:"O"}}) db.student.find("performance.marks"})

UPDATE in DB

Image
 db.student.updateOne({name:"abhi"},{$set:{marks:100}})  db.student.updateMany({city:"delhi"},{$set:{city:"New Delhi"}})  db.student.replaceOne({name:"dhoni"},{name:"thala",city:"chennai",marks:500})