What is mongoose?
- Mongoose is ODM (Object Document Modeling - or Mapping) that is used to connect MongoDB to our web project.
- SQL used ORM (Object Relational Modeling ), NoSQL used ODM.
- it's a module in npmJS.
Model and Schema
- Everything in Mongoose starts with a schema. Each Schema connect to a MongoDB collection and define the shape of the documents within that collections.
- 每個 schema 對應到一個 collection( model ), 並定義裡面的物件資料架構
- 'Models' are higher order constructors that take a schema and create an instance of a document equivalent to records in a database. (That's why we don't do finding in schema, instead, we do finding in model.)
- Model is just like a table in SQL, and schema is the creating table step.
- model(Mongoose) ≒ collection(MongoDB) ≒ table(SQL)
Connect to MongoDB
// import mod
const express = require('express');
const app = express();
const mongoose = require('mongoose');
// connect to MongoDB
mongoose
[.connect('mongodb://localhost/todo-list', {
useNewUrlParser: true,
useUnifiedTopology: true
}).](<https://mongoosejs.com/>)then(() => {
console.log('Connected to Mongo DB.');
}).catch((e) => {
console.log('Connection failed.');
console.log(e);
});
Define a schema instance(model)
// define a schema of a students model(collection)
const studentSchema = new mongoose.schema({
name: String,
age: Number,
major: String,
scholarship: {
merit: Number,
other: Number,
},
});
// create a model for students 將 Student 賦值為一個 studentSchema 型的實例物件
// 並且這個 model(collection) 會適用 mongoose 和 mongoDB 的方法
const Student = mongoose.model('Student', studentSchema);
Create An Object instance of model
// create an object of Student collection
// 這邊的做法就跟 JS 創建實例一樣,創建一個適用於 Student 資料表(collection) 的學生實例
const Andrew = new Student({
name: "Andrew Wu",
age: 25,
major: "IM",
scholarship: {
merit: 2500,
other: 1300
}
});
Save An instance to MongoDB BY Mongoose