Mongoose 是提供給 Node.js 使用的 MongoDB ODM。透過 Mongoose,我們可以用物件導向語法,以更直覺的方式操作 MongoDB 資料庫。
mkdir mongodb
cd mongodb
code .
npm init -y
npm install mongoose -p
//導入了 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);
});
});