※ Mongoose官網

※ 認識Mongoose
Mongoose 是提供給 Node.js 使用的 MongoDB ODM。透過 Mongoose,我們可以用物件導向語法,以更直覺的方式操作 MongoDB 資料庫。

※ Mongoose安裝

※ 建立資料夾:
mkdir mongodb
cd mongodb
code .
※ 建立檔案app.js:

※ 初始化,建立package.json:
npm init -y


※ 下載Mongoose:
npm install mongoose -p
※ 典型的 Mongoose 基本流程架構:
- 導入 Mongoose 模組:使用 require('mongoose') 將 Mongoose 模組導入到你的程式中。
- 連接 MongoDB 資料庫:通過 mongoose.connect 方法,並透過 db 這個 Promise 物件,來表示 Mongoose 連接資料庫的過程。
- 定義資料模型:使用 mongoose.model 方法,定義資料模型並設定每個文件的結構和驗證規則。
- 增刪改查:使用 Mongoose 的各種方法(如 insertMany、find、updateOne、deleteMany 等)進行資料的增刪改查操作。
※ 透過 Mongoose 來連接本地的 MongoDB 資料庫。
//導入了 Mongoose 模組
const mongoose = require('mongoose');
//MongoDB 資料庫的連接
const db = mongoose.connect('mongodb://localhost:27017/school');
※ 透過db
這個 Promise 物件,來表示 Mongoose 連接資料庫的過程。
db.then(mongo => {
console.log("Connected to MongoDB!");
});
※ 定義一個資料模型School
,並設定每個 School
文件的結構和驗證規則:
db.then(mongo => {
const School = mongo.model('School', {
name: String,
year: {
type: Number,
min: 5,
max: 10,
required: [true]
},
created_at: {
type: Date,
default: Date.now
}
})
});
※ 新增多筆資料:
db.then(mongo => {
const School = mongo.model('School', {
name: String,
year: {
type: Number,
min: 5,
max: 10,
required: [true]
},
created_at: {
type: Date,
default: Date.now
}
})
//新增多筆資料
School.insertMany([
{ name: '台灣大學', year: 10 },
{ name: '大學-2', year: 10 },
{ name: 'Js School', year: 8 }
])
.then(docs => {
console.log(docs);
})
.catch(err => {
console.error(err);
});
});
※ 更新資料:
db.then(mongo => {
const School = mongo.model('School', {
name: String,
year: {
type: Number,
min: 5,
max: 10,
required: [true]
},
created_at: {
type: Date,
default: Date.now
}
})//更新單筆資料
School.updateOne({ name: 'Js School' }, { $set: { year: 9 } })
.then(result => {
console.log('Update successful', result);
})
.catch(err => {
console.error(err);
});
//更新多筆資料
School.updateMany({ year: 10 }, { $set: { year: 11 } })
.then(result => {
console.log('Update successful', result);
})
.catch(err => {
console.error(err);
});
});
※ 查詢資料:
db.then(mongo => {
const School = mongo.model('School', {
name: String,
year: {
type: Number,
min: 5,
max: 10,
required: [true]
},
created_at: {
type: Date,
default: Date.now
}
})
//查詢資料
School.find({})
.then(docs => {
console.log(docs);
})
.catch(err => {
console.error(err);
});
});
※ 刪除資料:
db.then(mongo => {
const School = mongo.model('School', {
name: String,
year: {
type: Number,
min: 5,
max: 10,
required: [true]
},
created_at: {
type: Date,
default: Date.now
}
})
//刪除單筆資料
School.deleteOne({ _id: "67088f46b50c8cf8d6ceafeb" })
.then(() => {
console.log('Delete successful');
})
.catch(err => {
console.error(err);
});
//刪除多筆資料
School.deleteMany({})
.then(() => {
console.log('Delete successful');
})
.catch(err => {
console.error(err);
});
});