開場白
**MongoDB **是一個基于分布式文件存儲的非關(guān)系型數(shù)據(jù)庫奏篙,由C++語言編寫在旱,旨在為WEB應(yīng)用提供可擴(kuò)展的高性能數(shù)據(jù)存儲解決方案。推薦運(yùn)行在64位平臺虎敦,因為MongoDB在32位模式運(yùn)行時支持的最大文件尺寸為2GB酿愧,64位平臺則非常大沥潭。MongoDB中有三種元素:數(shù)據(jù)庫(database),集合(collection)嬉挡,文檔(document)钝鸽,其中“集合” 對應(yīng)關(guān)系數(shù)據(jù)庫中的“表”汇恤,“文檔”對應(yīng)關(guān)系數(shù)據(jù)庫的“行”。其中MongoDB 是文檔數(shù)據(jù)庫拔恰, 面向集合(collection)的數(shù)據(jù)庫因谎。
使用者留言
一個詞: 簡單, 沒有了傳統(tǒng)數(shù)據(jù)庫那么多的限制,讓開發(fā)者更多精力放在處理業(yè)務(wù)邏輯上仁连,學(xué)習(xí)曲線很平滑蓝角,因為沒有新的查詢語言學(xué)習(xí)。代碼是簡潔的饭冬。畢竟,無須任何其他ORM揪阶,封裝可以非常簡單昌抠。你的代碼是未來的保證。向你的對象增加更多的字段是很輕松的鲁僚。因此炊苫,需求變化了,你可以很快修改代碼以便適應(yīng)冰沙。
Node.js 中使用MongoDB(幾乎是標(biāo)配)
mac中安裝MongoDB
brew install mongodb
node.js 中使用mongoose第三方庫來管理MongoDB
npm install mongoose --save
為什么使用mongoose呢侨艾,原因很簡單,官方的驅(qū)動都是以回調(diào)的方式的API拓挥,而mongoose封裝成了promise唠梨,就可以使用await/async了
*配置連接DB信息,并導(dǎo)出連接的對象
import mongoose from 'mongoose'
const options = {
user: 'admin',
pwd: '123456',
host: 'localhost',
port: '27017',
database: 'hollywood',
authSource: 'admin',
}
const uri = `mongodb://${options.user}:${options.pwd}@${options.host}:${options.port}/${options.database}?authSource=${options.authSource}`
mongoose.Promise = global.Promise //需要
mongoose.connect(uri)
export default mongoose
*定義一個模型的概要,類似于關(guān)系型數(shù)據(jù)庫中的定義表結(jié)構(gòu)
import db from '../db.js'
import logger from '../logger'
const Schema = db.Schema
//account對應(yīng)的字段
const accountSchema = new Schema(
{
name: { type: String, maxlength: 15 },
password: { type: String, maxlength: 20 },
gender: { type: String, enum: ['male', 'female'] },
email: { type: String, maxlength: 25 },
avatar: { type: String },
age: { type: Number },
create_date: { type: Date },
update_date: { type: Date },
},
{
versionKey: false,
},
)
//當(dāng)account執(zhí)行save()前侥啤,執(zhí)行該代碼片段当叭,有點類似于中間件(這個方法內(nèi)容僅僅是介紹pre()的使用方法)
accountSchema.pre('save', function(next) {
const currentDate = new Date()
if (!this.create_date) {
this.create_date = currentDate
} else {
this.update_date = currentDate
}
next()
})
//當(dāng)account執(zhí)行save()后
accountSchema.post('save', function(doc) {
logger.info(`Account ${doc._id} was saved.`)
})
//定義模型的方法
accountSchema.methods.sayHi = () => (console.log('sayHi()!!!!!'))
const Account = db.model('Account', accountSchema)
export default Account
*保存到數(shù)據(jù)庫, 并返回一個保存到數(shù)據(jù)庫的對象
import Account from './model'
export default class AccountService {
static async save(json) {
const accountModel = new Account(json)
const account = await accountModel.save()
return account
}
}
CRUD的操作
R
Account.find({ name: 'yellow' })
U (完全可以自己在封裝一層)
const account = await Account.find({ name: 'yellow' })
account.name = 'hzc'
await account.save()
- D
const account = await Account.find({ name: 'yellow' })
await account.remove()
總結(jié)
使用確實方便,但是也會有很多坑等待你來挖盖灸,畢竟是新事物蚁鳖, 需要不斷的發(fā)展,但是你同它一起進(jìn)步赁炎,一起發(fā)展不是已經(jīng)很有意思的事情嗎醉箕。