Mongo Da Best
The M
2
Manipulating DB Data
Middlewares and instance methods
# FULLSTACK JS
What we mean here, is that we're gonna learn to use code to: find, update.. data in our DB
# FULLSTACK JS
async function findData(first_name){
try{
const users = await userModel.find({first_name});
return users;
}catch(e){
return [];
}
}
Find Data
# FULLSTACK JS
async function updateUserByID(_id, newData){
try{
const users = await userModel.updateOne({_id}, newData);
console.log("user has been updated")
return users;
}catch(e){
console.error(e);
}
}
# FULLSTACK JS
async function updateUserByID(_id){
try{
const users = await userModel.deleteOne({_id});
console.log("user has been deleted")
return users;
}catch(e){
console.error(e);
}
}
# FULLSTACK JS
# FULLSTACK JS
Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions.
# FULLSTACK JS
userSchema.pre('save', function(next) {
// do stuff
next();
});
Middlewares
userSchema.post('save', function(next) {
// do stuff
next();
});
Before saving
After saving
# FULLSTACK JS
The instances of models have many methods that are already built in (create, update.. etc) but we can have our customized ones
# FULLSTACK JS
//Define a schema
//
userSchema.methods.findSimilarAge = function (cb){
return mongoose.model('user').find({age : this.age}, cb)
}
//now all the users instaces have a findSimilarAge method available in them
//
//to try it:
//
const User = mongoose.model('User', userSchema)
const person = new User({age: 20}) //we instanciAgeate User
person.findSimilarAge((err, persons)=>{
console.log(persons);
})