Mongo DB & Mongoose 常用語法


Posted by pei_______ on 2022-06-18

Mongo shell - Documentation
Mongo shell CRUD - Documentation
Mongo native driver - Documentation
mongoose - Documentation


Mongo DB - by mongo shell


00. The First Time

  1. switch in vim
    $ vim .bash_profile
  2. switch to insert mode
    press i
  3. key in the path
    alias mongod="/c/Program\ files/MongoDB/Server/5.0/bin/mongod.exe"
    alias mongo="/c/Program\ Files/MongoDB/Server/5.0/bin/mongo.exe"
    
  4. quit the insert mode
    press esc
  5. save & exit vim
    :wq! + press Enter

01. Start & Check

# spin up mongo server (1st termial tap)
$ mongod 

# open new shell (switch to 2nd termial tap)
$ mongo

# check whole databases
> show dbs 
admin   0.000GB
config  0.000GB
local   0.000GB

# check using database
> db

# check collections
> show collections

02. Create

# create database - use %database name%
> use shopDB

# create collection ( = table)
> db.products.insertOne({_id: 1,name: "Pen", price: 1.20})

03. Read

# db.collection.find({ Query (option) },{ Projection (option) })
# 0 = fulse, 1 = true, _id = 1 in defult

> db.products.find()
> db.products.find({ name: "Pen" })
> db.products.find({ price: {$gt: 1} })
> db.products.find({ price: {$gt: 1}, {_id: 0, name: 1} })

04. Update

# db.products.updateOne( %update filter%, %update action% )
> db.products.updateOne( {_id: 1}, {$set: {stock: 32} )

05. Delete

# delete a document
> db.products.deleteOne( {_id:2} )

# delete all documents
> db.products.drop()

# delete database
> db.dropDatabase()

06. Build Relationship

db.products.insert({
  _id: 2,
  name: "Pencil",
  price: 0.80,
  stock: 12,
  reviews: [
  {
    authorName: "Sally",
    rating:5,
    review: "Good"
  },
  {
    authorName: "Jerry",
    rating: 4,
    review: "Great"
  }
  ]
})

Mongo DB & JS - by native driver



/* ---------- 01. Set & Connect ---------- */

const { MongoClient } = require("mongodb");

// Connection URI
const uri = "mongodb://localhost:27017";

// Create a new MongoClient
const client = new MongoClient(uri);

async function run() {

  try {
    // Connect the client to the server
    await client.connect();

    // Establish and verify connection
    await client.db("fruitsDB").command({ ping: 1 });
    console.log("Connected successfully to server");


/* ---------- 02. insert Document ---------- */

    const db = client.db("fruitsDB");
    const fruits = db.collection("fruits");
    const docs = [
        { name: "Apple", score: 8 , review: "Great" },
        { name: "Banana", score: 7 , review: "Good" },
        { name: "Orange", score: 10 , review: "Awesome!" },
    ];


    // Insert and verify insertion
    const resultOfCreate = await fruits.insertMany(docs);
    console.log("Documents was inserted");


/* ---------- 03. find Specific Data ---------- */

    // Query for scores that are greater than 7
    const query = { score: {$gt: 7} };

    // Optional projection for returned document
    const options = {

      // sort matched documents in descending order by rating
      sort: { "score": -1 },

      // Include only the `name` and `review` fields in the returned document
      projection: { name: 1, score: 1, review: 1 },
    };

    const resultOfFind = await fruits.findOne(query, options);
    // since the method returns matched documents, not a cursor, print it
    console.log(resultOfFind);


/* ---------- 04. close after finish or error ---------- */

  } finally {

    // Ensures that the client will close when you finish/error
    await client.close();
  }
}

run().catch(console.dir);

Mongo DB & JS - by mongoose


01. Set & Connect

$ npm i mongoose

const mongoose = require("mongoose");

// 1. make connection to MongoDB sever
// 2. look for a database called fruitsDB

mongoose.connect("mongodb://localhost:27017/fruitsDB");

02. Create Schema / Model / A Document / Documents

/* ---------- 01. Create Schema ---------- */

// 1. create a schema (= structure of collection)
// 2. as like to create a structure of table in SQL

const fruitSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, "Name is required"]
  },
  rating: {
    type: Number,
    min: 1,
    max: 10
  },
  review: String
});


/* ---------- 02. Create Model ---------- */

// 3. build a model (= collection)
// 4. as like to create a table in SQL
// 5. first input: name of the collection (in singular form)
// 6. second input: structure of the collection

const Fruit = mongoose.model("Fruit", fruitSchema)


/* ---------- 03. Create A Document ---------- */

// 7. create a document from model

const fruit = new Fruit({
  name: "Peach",
  rating: 5,
  review: "Great"
})

// 8. save a document in FruitsDB
fruit.save();


/* ---------- 04. Create Many Documents ---------- */

// 9. save many documents in FruitsDB
// 10. first input: array of objects
// 11. second input: callback fuction

Fruit.insertMany([kiwi, banana], function(err) {
    if (err) {
    console.log(err);
    } else {
        console.log("Successful saved all the fruits");
    }
    })

03. Read (Find) datas

// 1. find all datas

Fruit.find(function(err, fruits) {
  if (err) {
    console.log(err);
  } else {
    fruits.forEach(function(fruit) {
      console.log(fruit.name);
    });
  }
});

// 2. find a specific data
Post.findOne({_id: requestedPostId}, function(err, post){ }

04. Update datas

// 1. first input: filter
// 2. second input: update what?
// 3. third input: callback funcion

Person.updateOne({
  _id: "62adc673ebc56169ce42f315"
}, {
  favouriteFriut: banana
}, function(err) {
  if (err) {
    console.log(err);
  } else {
    console.log("Successful update.")
  }
})

05. Delete A data / datas

/* ---------- 01. Delete A Data ---------- */

// 1. first input: filter
// 2. second input: callback funcion

Person.deleteOne({_id: "62adcaf8f4d422b9b38983ec"}, function(err) {
  if (err){
    console.log(err);
  } else {
    console.log("Successful delete.")
  }
})


/* ---------- 02. Delete Many Datas ---------- */

// 1. first input: filter
// 2. second input: callback funcion

Fruit.deleteMany({
      name: "Apple"
    }, function(err) {
      if (err) {
        console.log(err);
      } else {
        console.log("Successful delete all.")
      };})

06. Close Mongoose after done

mongoose.connection.close()

#Mongo DB #Mongoose #web系列







Related Posts

DAY 02 : 演算法基本概念

DAY 02 : 演算法基本概念

在迴圈內依條件判斷新增元素

在迴圈內依條件判斷新增元素

[ 筆記 ] JavaScript 進階 03 - Execution Context - Variable Object

[ 筆記 ] JavaScript 進階 03 - Execution Context - Variable Object


Comments