Mongoose Documentation

Munisekhar Udavalapati - Aug 9 - - Dev Community

Mongoose is a popular library for MongoDB in Node.js and JavaScript.it simplifies complex queries, making them more understandable and easier to work with.
connecting to Mongoose in our application
app.js

const mongoose=require('mongoose');
//your code here
mongoose
 .connect('mongodb://localhost:27017')
 .then(res=>app.listen(3000))
 .catch(err=>console.log(err));
Enter fullscreen mode Exit fullscreen mode

To create a scheme
models/student.js

const mongoose=require('mongoose');
const {Schema}=mongoose;
const schema= new Schema({
 name:{
  type:String, //name is string
  required:true, // Ensure name is provided
  trim:true  // Automatically trim whitespace
 },
 id:{
  type:Number,
  required:true,
  unique:true,
  index:true
 }

});
module.exports=mongoose.model('Students',schema);
Enter fullscreen mode Exit fullscreen mode

add the data to database schema
controllers

 const students=require('./models/student.js');

 const student = new students({
  name:'munisekhar',
  id:44
 });

 student.save()
 .then(res=>console.log('student added'))
 .catch(err=>console.log(err));
Enter fullscreen mode Exit fullscreen mode

Get all data from database schema where name=sekhar

 const students=require('./models/student.js');
 const data= await students.find({name:'sekhar'})
Enter fullscreen mode Exit fullscreen mode

Get data from database schema by using id

 const students=require('./models/student.js');
 const data= await students.findById({id:7})
Enter fullscreen mode Exit fullscreen mode

Get data from database schema by using name

 const students=require('./models/student.js');
 const data= await students.findOne({name:sekhar});
Enter fullscreen mode Exit fullscreen mode

Update data from database schema

 const students=require('./models/student.js');
 const uapdateStudent= await students.findOneAndUpdate(
  {id:7},
  {name:'ram'}
 )
Enter fullscreen mode Exit fullscreen mode

Delete data from database schema

 const students=require('./models/student.js');
 const deleteStudent= await students.findOneAndDelete({id:7})
Enter fullscreen mode Exit fullscreen mode
 const students=require('./models/student.js');
 const student= await students.findOne({id:7})
 await student.deleteOne();
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . .