connect to Mongo db:

install mongoose package : npm i mongoose

import mongoose

mongoose
  .connect("mongodb://<mongo-db-server | localhost>/<database-name>")
  .then(() => console.log("Connected to database"))
  .catch((err) => console.error("Database connection fail", err));

After connecting to the database, next thing we need to do is create a schema,

we use schema to shape our document within a collection

collection is like table in Relational database

collection → table

document → row

schema → define the shape of the document

const courseSchema = new mongoose.Schema({
  name: String,
  author: String,
  tags: [String],
  date: { type: Date, default: Date.now },
  isPublished: Boolean,
  price: Number,
});

list of types that we can use while creating schema:

  1. String
  2. Number
  3. Date
  4. Buffer → to store binary data
  5. Boolean
  6. ObjectID
  7. Array

Now we need to compile this to model

// compiling schema into model
const Course = mongoose.model("Course", courseSchema);

the first argument is → name of the collection “course” The second argument is the shape of the document or schema

Create:

async function createCourse() {
	const course = new Course({
    name: "React Native",
    author: "Stephen Grider",
    tags: ["react", "mobile"],
    isPublished: true,
    price: 1499,
  });
  
  const course1 = await course.save();
 }

mongo → document is a complex object, it can have an array of strings,

We don’t have to define the structure, we just can define object and save them.

Read:

async function getCourses() {
  return await Course.find().or([
    { price: { $gte: 1600 } },
    { name: /.*doc.*/i },
  ]);
}

methods:

  1. find → list of documents

    Filter

    async function getCourses() {
      return await Course.find({author:"mosh", isPublished:true});
    }
    
  2. findbyId →

Comparison:

  1. eq → equal
  2. ne → not equal
  3. gt → greater than
  4. gte→ greater than or equal to
  5. lt → less than
  6. lte→ less than or equal to
  7. in →
  8. nin → not in
const courses = await Course
		.find({price:{$gte: 10}}) // greater than 10
		//.find({price:{$gte:10, $lte: 20}}) // between 10 and 20$
		.limit(10)
		.sort({name:1})
		// only return this 
		.select({name:1, tags:1})

Logical operators:

async function getCourses() {
  return await Course
  .find()
  .or([{author:"Mosh"}, {isPublished:true}])
  .limit(10)
  .sort({name:1});
}
async function getCourses() {
  return await Course
  .find()
  .and([{author:"Mosh"}, {isPublished:true}])
  .limit(10)
  .sort({name:1});
 
}
async function getCourses() {
  return await Course
  // starts with mosh 
  //.find({author:/pattern/})
  .find({author:/^Mosh/}) 
  
  // ends with 
  .find({author:/Hamedani$/}) 
  
  // to make it case insensitive -> add I at the end 
	.find({author:/^Mosh/i})
	
	// author contains mosh
	.find({author:/.*Mosh.*/i})
  .limit(10)
  .sort({name:1});
}
const courses = await Course
		.find({price:{$gte: 10}}) // greater than 10
		//.find({price:{$gte:10, $lte: 20}}) // between 10 and 20$
		.limit(10)
		.sort({name:1})
		// only return this 
		.count()
const pageNumber = 2;
const pageSize = 10;

// /api/courses?pageNumber=2&pageSize=10

const course = await Course
	.find()
	.skip((pageNumber - 1 ) * pageSize)
	.limit(pageSize)
mongoimport --db <database-name> --collection <collection-name> --file <filename> --<type of data> eg: jsonArray 

Update:

There are 2 ways of updating document

  1. Query first
    1. findByID()
    2. Modify
    3. Save()
  2. Update first
    1. UpdateDirectly
    2. Get the updated Document

Query first

 //first query and update
 async function updateCourse(id) {
   const course = await Course.findById(id);
   
   if (!course) return dbDebug("No course with given ID");

   course.author = "Mr. Bean Jr";
   course.isPublished = false;
   
   // another method is to use set method: 
   course.set({
	   isPublished: true,
	   author: 'Mr. Bean'
   });
   
   const result = await course.save();
   console.log(course);
 }

Update Directly:

async function updateCourse(id) {
  const course = await Course.findByIdAndUpdate(
  // query | filter object
    { _id: id },

	// update object
    {
      $set: {
        author: "jack ma",
        isPublished: false,
      },
    },

// this will return the updated data 
    { new: true }
  );
  console.log(course);
}

Delete:

async function deleteCourse(id) {
  const course = await Course.findByIdAndDelete(id);
  console.log(course);
}

Document: