Mongoose的模塊化
目錄
Mongoose的模塊化
1.建立一個model檔案夾,其中建一個db.js連接資料庫 進行包裝匯出
2.在model檔案中建立需要的表 ,例:news ,user
3.進行增差改除4項操作


運用了模塊化,使用不同的模塊,對相應的操作進行包裝,操作起來非常簡單,2
1.建立一個model檔案夾,其中建一個db.js連接資料庫 進行包裝匯出
連接引數說明:
第一個引數為資料庫的地址,如果設定了密碼的話,記得加上用戶名和密碼,格式如下:
mongodb://localhost/text,fn
第二個引數 useNewUrlParser 屬性會在url里識別驗證用戶所需的資料庫
第三個引數 為回呼函式用來確認資料庫是否連接成功,
var mongoose = require('mongoose'); mongoose.connect('mongodb://127.0.0.1:27017/test', { useNewUrlParser: true }, function (err) { if (err) { console.log(err); return; } console.log('資料庫連接成功') }); module.exports = mongoose
在這我用的是news表 引入db.js 將一切news表需要的內容包裝起來
var mongoose = require('./db') var NewSchema = mongoose.Schema({ 'name': String, "staus": { type: Number, default: 1 }, }) var NewModel = mongoose.model('NewModel', NewSchema, 'news'); module.exports = NewModel
3.進行增差改除4項操作
1) 新增資料
NewModel.insertMany({ "name": 'jing' }, function(err, res) { if (err) { console.log(err) } console.log(res) });2) 修改資料
NewModel.updateMany({ "name": 'jing' }, { 'staus': 3 }, function(err, res) { if (err) { console.log(err) } console.log(res) });3) 查找所有資料,想如果想查找相應資料在find中添加josn陳述句就可以 ,可以加where條件限制
NewModel.find({}, function(err, res) { if (err) { console.log(err) } console.log(res) });4)洗掉資料
NewModel.remove({ "name": 'jing' }, function(err, res) { if (err) { console.log(err) } console.log(res) });
大家可能發現在定義schema時,引入了db.js檔案,即連接了一次資料庫,那么呼叫多個schema時,是否會多次連接資料庫了,其實在mongoose的底層已經做了單例模式的處理,也就是說只會在第一次連接時比較耗時,后續的連接執行都會很快,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/293924.html
標籤:其他
