1. Connection to MongoDB using Mongoose:
Create a Database in MongoDB Atlas>
To create Database in MongoDB atlas refer: https://www.mongodb.com/docs/atlas/create-database-deployment/
const connectionInstance = async()=>{
try {
const connection= await mongoose.connect("Connection URL")
console.log("MogoDB connection successfull");
} catch (error) {
console.log("MongoDB Error: ", error)
process.exit(1)
}
}
2. Create Basic Schema
In Mongoose, a schema serves as a blueprint for defining the structure of a Mongoose model. Let’s break it down:
Schema Definition:
A schema is a configuration object that specifies how the data in a Mongoose model should be organized.
It defines the fields, their types, default values, and any validation rules that should be applied to the data.
Model vs. Schema:
A model represents a MongoDB collection and provides an interface for creating, querying, updating, and deleting records based on the schema.
A schema, on the other hand, defines the structure of a document or record within that collection.
What Schemas Do:
Define the properties that documents saved in MongoDB can have.
Declare custom validation rules.
Specify virtuals (computed properties).
Define getters and setters for transforming data.
Declare static methods for querying the database based on the schema.
import mongoose from "mongoose";
const userSchema= new mongoose.Schema({
firstname:{
type:String,
required: true
},
lastname:{
type:String,
required: true
},
email:{
type:String,
required: true
},
dob:{
type:Date,
required: true
},
},{timestamps:true})
export const User= mongoose.model("User",userSchema)
//it will create a database for the define shema and set the name in lowercase in pulalr form
//e.g User --> users
3. Fetch All records
To fetch records we can use find() method. Generally find method will take a filter ({name:"somename"}) in the argument but to fetch all records you can just give {} in argument
//get all records(files) from MongoDB
const users=await User.find({})
console.log(users);
4. Insert new Record
// Inser new user in MongoDb using Mongoose
const newUser = new User()
newUser.firstname="Akash"
newUser.lastname="Chauhan"
newUser.email="akash@akash.com"
newUser.dob=Date.now()
const savedUser= await newUser.save()
console.log(savedUser);
5. Update the Records
By fetching the records and update it and then save the schema using save method
const userToBeUpdated= await User.findOne({firstname:"Akash"})
console.log("User: ", userToBeUpdated);
userToBeUpdated.email="akash.akash@gmail.com"
const updatedUser=await userToBeUpdated.save()
console.log("updated User: ", updatedUser);
By moongoose FindOneAndUpdate method
const updatedUser= await User.findOneAndUpdate(
{
firstname:"Akash" //filter for which name you want to change the values
},
{
email:"akas.akash@akash.com" //Values that you want to change
},
{
new:true
}
)
console.log(updatedUser);