Node.js的MongoDB驅動Mongoose基本上使用教學_node.js
使用mongoose可以讓我們更好地使用mongodb資料庫,而不需要寫繁瑣的業務邏輯。
安裝
npm install mongoose
初始化使用
使用mongoose前,需安裝node和mongodb,這裡不講node和mongodb的安裝方法。
var mongoose = require("mongoose"); var Schema = mongoose.Schema; var db = mongoose.connection; mongoose.connect('mongodb://localhost/animal'); db.on('error', console.error); db.once('open', function() { //这里建立模式和模型 }
快速入門
在mongoose中,所有的資料都是一種模式,每個模式都會對應到mongodb的集合,並且定義該集合檔案結構。
//这里建立一个动物的模式,所有动物都拥有这个模式下的所有属性 var animalSchema = new Schema({ name: String, age: Number, });
模型是我們從Schema定義的一種多樣化的建構函數,模型的實例可以使用很多操作,所有文件的建立和檢索都是由模型來處理
var animalMode = db.model('Animal', animalSchema);
模型的實例實質是文件,而我們可以很輕鬆地建立、修改這種文件
var cat = new animalMode({ name: 'catName', age: '7', //这里依然使用字符串,mongoose会自动转换类型 }); cat.save(function(err, thor) { if (err) return console.log(err); console.log(thor); }); //或者可以使用create //cat.create(function(err, thor) { // if (err) return console.log(err); // console.log(thor); //}); //执行查找 animalMode.find(function(err, people){ if(err) console.log(err); console.log(people); }); //查找符合条件数据 animalMode.findOne({title: 'catName'}, function(err, cat){ if(err) console.log(err); console.log(cat); });
Schema
資料型別
這是Schema中所有的資料類型,包括mongoose自定的資料類型
- String
- Number
- Date
- Buffer
- Boolean
- Mixed
- ObjectId
- Array
每種資料類型的使用
var animalMode = mongoose.model('Animal', schema); var cat = new animalMode; cat.name = 'Statue of Liberty' //String cat.age = '7'; //Number cat.updated = new Date; //Date cat.binary = new Buffer(0); //Buffer cat.living = false; //Boolean cat.mixed = { any: { thing: 'i want' } }; //Mixed cat._someId = new mongoose.Types.ObjectId; //ObjectId cat.ofString.push("strings!"); //Array
其中Mixed是mongoose自訂的混合型,因為Mixed沒有定義具體內容,可以用{}來使用,以下2種定義形式等價。
var animalSchema = new Schema({any: {}}); var animalSchema = new Schema({any: {Schema.Types.Mixed}});
自訂方法
可以為Schema綁定方法
var animalSchema = new Schema({ name: String, age: Number, }); animalSchema.methods.findSimilarTypes = function (cb) { return this.model('Animal').find({ name: this.name }, cb); } var animalMode = db.model('Animal', animalSchema); cat.findSimilarTypes(function(err, cat){ if(err) console.log(err); console.log(cat); });
也可以為Schema加入靜態方法
animalSchema.statics.findByName = function (name, cb) { return this.find({ name: new RegExp(name, 'i') }, cb); } var animalMode = db.model('Animal', animalSchema); animalMode.findByName('catName', function (err, animals) { console.log(animals); });
索引
我們可以為mongodb資料建立索引,mongodb支援二級索引,為了提高資料查找和定位,建立複合索引是必要的
var animalSchema = new Schema({ name: String, age: Number, tags: { age: [String], index: true } // field level }); animalSchema.index({ name: 1, age: -1 }); // schema level
但這種索引的建立可能導致顯著的效能影響,建議在生產下停止,將設定模式下的自動索引設為false禁止
animalSchema.set('autoIndex', false); // or new Schema({..}, { autoIndex: false });
Model
C
cat.save(function(err, thor) { if (err) return console.log(err); console.log(thor); }); //或者可以使用create cat.create(function(err, thor) { if (err) return console.log(err); console.log(thor); });
R
//find animalMode.find(function(err, cat){ if (err) console.log(err); console.log(cat); }) //findOne animalMode.findOne({name: 'catName'}, function(err, cat){ if (err) console.log(err); console.log(cat); }) //findByID //与 findOne 相同,但它接收文档的 _id 作为参数,返回单个文档。_id //可以是字符串或 ObjectId 对象。 animalMode.findById(id, function(err, adventure){ if (err) consoel.log(err); console.log(adventure); }); //where //查询数据类型是字符串时,可支持正则 animalMode.where('age', '2').exec(function(err, cat){ if (err) console.log(err); console.log(cat); }); animalMode .where('age').gte(1).lte(10) .where('name', 'catName') .exec(function(err, cat){ if (err) console.log(err); console.log(cat); });
U
官方文件提供的更新函數Model.update
Model.update(conditions, doc, [options], [callback])
- conditions 更新條件
- doc 更新內容
- option 更新選項
- safe (boolean) 安全模式,預設選項,值為true
- upsert (boolean) 條件不符時是否建立新文檔,預設值為false
- multi (boolean) 是否更新多個文件,預設值為false
- strict (boolean) 嚴格模式,只更新一條資料
- overwrite (boolean) 覆蓋數據,預設為false
- callback
- err 更新資料出錯時回傳值
- numberAffected (筆者暫時不清楚)
- rawResponse 受影響的行數
animalMode.update({name: 'catName'}, {age: '6'}, {multi : true}, function(err, numberAffected, raw){ if (err) return console.log(err); console.log('The number of updated documents was %d', numberAffected); console.log('The raw response from Mongo was ', raw); });
D
animalMode.remove({age: 6}, function(err){ if (err) console.log(err); })
其它
//回傳文檔數
animalMode.count({age: 2}, function(err, cat){ if (err) console.log(err); console.log(cat); })

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

在開發一個電商網站時,我遇到了一個棘手的問題:如何為用戶提供個性化的商品推薦。最初,我嘗試了一些簡單的推薦算法,但效果並不理想,用戶的滿意度也因此受到影響。為了提升推薦系統的精度和效率,我決定採用更專業的解決方案。最終,我通過Composer安裝了andres-montanez/recommendations-bundle,這不僅解決了我的問題,還大大提升了推薦系統的性能。可以通過一下地址學習composer:學習地址

本文介紹如何在Debian系統上配置MongoDB實現自動擴容,主要步驟包括MongoDB副本集的設置和磁盤空間監控。一、MongoDB安裝首先,確保已在Debian系統上安裝MongoDB。使用以下命令安裝:sudoaptupdatesudoaptinstall-ymongodb-org二、配置MongoDB副本集MongoDB副本集確保高可用性和數據冗餘,是實現自動擴容的基礎。啟動MongoDB服務:sudosystemctlstartmongodsudosys

本文介紹如何在Debian系統上構建高可用性的MongoDB數據庫。我們將探討多種方法,確保數據安全和服務持續運行。關鍵策略:副本集(ReplicaSet):利用副本集實現數據冗餘和自動故障轉移。當主節點出現故障時,副本集會自動選舉新的主節點,保證服務的持續可用性。數據備份與恢復:定期使用mongodump命令進行數據庫備份,並製定有效的恢復策略,以應對數據丟失風險。監控與報警:部署監控工具(如Prometheus、Grafana)實時監控MongoDB的運行狀態,並

直接通過 Navicat 查看 MongoDB 密碼是不可能的,因為它以哈希值形式存儲。取回丟失密碼的方法:1. 重置密碼;2. 檢查配置文件(可能包含哈希值);3. 檢查代碼(可能硬編碼密碼)。

CentOS系統下MongoDB高效備份策略詳解本文將詳細介紹在CentOS系統上實施MongoDB備份的多種策略,以確保數據安全和業務連續性。我們將涵蓋手動備份、定時備份、自動化腳本備份以及Docker容器環境下的備份方法,並提供備份文件管理的最佳實踐。手動備份:利用mongodump命令進行手動全量備份,例如:mongodump-hlocalhost:27017-u用戶名-p密碼-d數據庫名稱-o/備份目錄此命令會將指定數據庫的數據及元數據導出到指定的備份目錄。

CentOS系統上GitLab數據庫部署指南選擇合適的數據庫是成功部署GitLab的關鍵步驟。 GitLab兼容多種數據庫,包括MySQL、PostgreSQL和MongoDB。本文將詳細介紹如何選擇並配置這些數據庫。數據庫選擇建議MySQL:一款廣泛應用的關係型數據庫管理系統(RDBMS),性能穩定,適用於大多數GitLab部署場景。 PostgreSQL:功能強大的開源RDBMS,支持複雜查詢和高級特性,適合處理大型數據集。 MongoDB:流行的NoSQL數據庫,擅長處理海

在Debian系統上為MongoDB數據庫加密,需要遵循以下步驟:第一步:安裝MongoDB首先,確保您的Debian系統已安裝MongoDB。如果沒有,請參考MongoDB官方文檔進行安裝:https://docs.mongodb.com/manual/tutorial/install-mongodb-on-debian/第二步:生成加密密鑰文件創建一個包含加密密鑰的文件,並設置正確的權限:ddif=/dev/urandomof=/etc/mongodb-keyfilebs=512

要設置 MongoDB 用戶,請按照以下步驟操作:1. 連接到服務器並創建管理員用戶。 2. 創建要授予用戶訪問權限的數據庫。 3. 使用 createUser 命令創建用戶並指定其角色和數據庫訪問權限。 4. 使用 getUsers 命令檢查創建的用戶。 5. 可選地設置其他權限或授予用戶對特定集合的權限。
