Skip to content

yunji0387/Mongo-Mongoose-Commands

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 

Repository files navigation

Mongo/Mongoose Commands

A list of basic Mongo commands and Mongoose commands

Mongo Bash Commands

Connect to local server (In bash)

(click to expand/hide)
  1. activate local server port
  • mongod
  • activate success when we see "Waiting for connection" and port number Image
  1. connect with mongo shell
  • mongosh

If you forgot to quit the Mongod Server and close to terminal

(click to expand/hide)
  1. Open a new terminal
  2.  sudo pkill -f mongod
  3. Enter you password

Show all database

(click to expand/hide)
  • show dbs

Create Operation

(click to expand/hide)

Create a new database

  • use <database name>

Insert a data to database

  • db.<database name>.insertOne(
      {
        name: "tim",
        age: 26
      }
    )
  • if database does not exist, it will create one.

Insert a data with many subData (one to many relationship)

  • db.<database name>.insertOne(
      {
        name: "tim",
        age: 26,
        achievement:[
          {
            title: "cap",
            year: 2021
          },
          {
            title: "gold",
            year: 2023
          }
        ]
      }
    )

Read Operation

(click to expand/hide)

Find specific data

  • db.<database name>.find(
      {
        name: "tim",
        age: 26
      }
    )

Find data in specific bound

  • find data in database that has age > 10
  • db.<database name>.find(
      {
        age: {$gt: 10}
      }
    )

Find data with specific return

  • find data in database that has age > 10 and return with name and id
  • 0 = do not show, 1 = show
  • db.<database name>.find(
      {
        age: {$gt: 10}
      },
      {
        _id: 0,
        name: 1
      }
    )

Update Operation

(click to expand/hide)

update a specific data

  •  db.<database name>.updateOne(
       {
         _id: 1
       },
       {
         $set: {title: 15}
       }
     )

Delete Operation

(click to expand/hide)

delete a database

  1. switch to the database
  •   use <database name>
  1. delete the database
  •   db.dropDatabase()

delete a specific data

  •  db.<database name>.deleteOne(
       {
         _id: 1
       }
     )
  • delete successful if return acknowledged: true, and deletedCount: 1

include npm libraries in bash in your project directory

(click to expand/hide)
  •  npm i mongoose

Connect to mongoDB database in nodejs

(click to expand/hide)
  1. require package
    •  const mongoose = require("mongoose"); 
  2. connect to mongoDB database
    • connect to database with local host
    •   mongoose.connect("mongodb://localhost:27017/<database name>", { useNewUrlParser: true });

Disconnect to mongoDB database in nodejs

(click to expand/hide)
  •   mongoose.connection.close();
(click to expand/hide)
  •   const <schema name> = new mongoose.Schema({
            name: {
              type: String,
              required: [true, "Please check your data entry, no name specified!"]
            },
            rating: {
              type: Number,
              min: 1,
              max: 10
            },
            review: String
          });

Establishing Relationships and Embedding Documents

(click to expand/hide)
  •   const schema1 = new mongoose.Schema({
            name: {
              type: String,
              required: [true, "Please check your data entry, no name specified!"]
            },
            rating: {
              type: Number,
              min: 1,
              max: 10
            },
            review: String
          });
          
     const schema2 = new mongoose.Schema({
          name: String,
          age: Number,
          FavouriteBook: schema1
     }); 

Create Operation

(click to expand/hide)

create New Schema and Model(collection)

  1.   const <schema name> = new mongoose.Schema({
        name: String,
        rating: Number,
        review: String
      });
  2.   const <Model name> = mongoose.model("<Database name> without s", <schema name>);
  • model name's first letter usually written in Capital letter

insert new object(document) to databse

  •   const obj = new <Model name>({
        <key>: <value>,
        <key>: <value>,
        <key>: <value>
      });
      
      const obj.save();

insert many objects(documents) to database

  •   const obj1 = new <Model name>({
        <key>: <value>,
        <key>: <value>,
        <key>: <value>
      });
      
      <Model name>.insertMany([obj1, obj2, obj3])
         .then(function(){
             console.log("Successfully add item list to database.");
         })
         .catch(function(err){
             console.log(err);
         });
      
      // Alternate version
      /*
      <Model name>.insertMany([obj1, obj2, obj3])
         .then(() => {
             console.log("Successfully add item list to database.");
         })
         .catch((err) => {
             console.log(err);
         });
      */

Read operation

(click to expand/hide)

read all objects(documents) in database

  •   <Model name>.find({})
         .then(function(<result name>){
             console.log("Successfully add item list to database.");
         })
         .catch(function(err){
             console.log(err);
         });

Update operation

(click to expand/hide)

update an object(document) in database

  •   <Model name>.updateOne({_id: "123123"} , {name: "newName"}, function(err){
        if(err){
          console.log(err);
        }else{
          console.log("Successfully updated the document.");
        });

Delete operation

(click to expand/hide)

delete an object(document) in database

  •   <Model name>.deleteOne({_id: "123123"})
        .then(function(){
              console.log("Successfully deleted item");
          })
          .catch(function(err){
              console.log(err);
          });

delete multiple objects(documents) in database

  •   <Model name>.deleteMany({name: "John"})
        .then(function(){
              console.log("Successfully deleted items");
          })
          .catch(function(err){
              console.log(err);
          });

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published