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));
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);
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));
Get all data from database schema where name=sekhar
const students=require('./models/student.js');
const data= await students.find({name:'sekhar'})
Get data from database schema by using id
const students=require('./models/student.js');
const data= await students.findById({id:7})
Get data from database schema by using name
const students=require('./models/student.js');
const data= await students.findOne({name:sekhar});
Update data from database schema
const students=require('./models/student.js');
const uapdateStudent= await students.findOneAndUpdate(
{id:7},
{name:'ram'}
)
Delete data from database schema
const students=require('./models/student.js');
const deleteStudent= await students.findOneAndDelete({id:7})
const students=require('./models/student.js');
const student= await students.findOne({id:7})
await student.deleteOne();