mongodb參考
mongoose官網
mongoose用起來更便捷,更方便些??
使用mongodb資料驅動寫一個錯誤日志
更多有關node官方資料驅動mongodb參考檔案
這里沒有使用asset斷言
import mongodb from 'mongodb'
const MongoClient = mongodb.MongoClient
const url = 'mongodb://localhost:27017/edu'
export default (errLog, req, res, next) => {
// 1. 將錯誤日志記錄到資料庫,方便排查錯誤
// 2. 發送回應給用戶,給一些友好的提示資訊
// { 錯誤名稱:錯誤資訊:錯誤堆疊:錯誤發生時間 }
// 1. 打開連接
MongoClient.connect(url, (err, db) => {
db
.collection('error_logs')
.insertOne({
name: errLog.name,
message: errLog.message,
stack: errLog.stack,
time: new Date()
}, (err, result) => {
res.json({
err_code: 500,
message: errLog.message
})
})
// 3. 關閉連接
db.close()
})
}
存盤結構
- 一個計算機上可以有一個資料庫服務實體
- 一個資料服務實體上可以有多個資料庫
- 一個資料庫中可以有多個集合
- 集合根據資料的業務型別劃分
- 例如用戶資料、商品資訊資料、廣告資訊資料,,,
- 對資料進行分門別類的存盤
- 集合在 MongoDB 中就類似于陣列
- 一個集合中可以有多個檔案
- 檔案在 MongoDB 中就是一個 類似于 JSON 的資料物件
- 檔案物件是動態的,可以隨意的生成
- 為了便于管理,最好一個集合中存盤的資料一定要保持檔案結構的統一(資料完整性)
{
collection1: [
{ a: { age: 18, name: '', lsit: [], is: true } },
{ 檔案2 },
{ 檔案3 }
],
collection2: [
],
collection3: [
],
collection4: [
],
}
使用mongoose
Mongoose
安裝:
# npm install --save mongoose
yarn add mongoose
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test')
// 1. 創建一個模型架構,設計資料結構和約束
const studentSchema = mongoose.Schema({
name: String,
age: Number
})
// 2. 通過 mongoose.model() 將架構發布為一個模型(可以把模型認為是一個建構式)
// 第一個引數就是給你的集合起一個名字,這個名字最好使用 帕斯卡命名法
// 例如你的集合名 persons ,則這里就命名為 Person,但是最終 mongoose 會自動幫你把 Person 轉為 persons
// 第二個引數就是傳遞一個模型架構
const Student = mongoose.model('Student', studentSchema)
// 3. 通過操作模型去操作你的資料庫
// 保存實體資料物件
const s1 = new Student({
name: 'Mike',
age: 23
})
s1.save((err, result) => {
if (err) {
throw err
}
console.log(result)
})
//查詢
Student.find((err, docs) => {
if (err) {
throw err
}
console.log(docs)
})
Student.find({ name: 'Mike' },(err, docs) => {
if (err) {
throw err
}
console.log(docs)
})
更多操作參考檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/153407.html
標籤:JavaScript
上一篇:nvm,nrm和yarn
下一篇:使用mongoose--寫介面
