What is mongoose?

Model and Schema

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