Node.js的MongoDB驅(qū)動(dòng)Mongoose基本使用教程
使用mongoose可以讓我們更好使用mongodb數(shù)據(jù)庫(kù),而不需要寫(xiě)繁瑣的業(yè)務(wù)邏輯。
安裝
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() {
//這里建立模式和模型
}
快速入門(mén)
在mongoose中,所有的數(shù)據(jù)都是一種模式,每個(gè)模式都映射到mongodb的集合,并且定義該集合文件結(jié)構(gòu)。
//這里建立一個(gè)動(dòng)物的模式,所有動(dòng)物都擁有這個(gè)模式下的所有屬性
var animalSchema = new Schema({
name: String,
age: Number,
});
模型是我們從Schema中定義的一種多樣化的構(gòu)造函數(shù),模型的實(shí)例可以使用很多操作,所有文檔的創(chuàng)建和檢索都是由模型來(lái)處理
var animalMode = db.model('Animal', animalSchema);
模型的實(shí)例實(shí)質(zhì)是文件,而我們可以很輕松創(chuàng)建、修改這種文件
var cat = new animalMode({
name: 'catName',
age: '7', //這里依然使用字符串,mongoose會(huì)自動(dòng)轉(zhuǎn)換類(lèi)型
});
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);
//});
//執(zhí)行查找
animalMode.find(function(err, people){
if(err) console.log(err);
console.log(people);
});
//查找符合條件數(shù)據(jù)
animalMode.findOne({title: 'catName'}, function(err, cat){
if(err) console.log(err);
console.log(cat);
});
Schema
數(shù)據(jù)類(lèi)型
這是Schema中所有的數(shù)據(jù)類(lèi)型,包括mongoose自定的數(shù)據(jù)類(lèi)型
- String
- Number
- Date
- Buffer
- Boolean
- Mixed
- ObjectId
- Array
每種數(shù)據(jù)類(lèi)型的使用
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自定義的一種混合類(lèi)型,因?yàn)镸ixed沒(méi)有定義具體內(nèi)容,可以用{}來(lái)使用,以下2種定義形式等價(jià)。
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添加靜態(tài)方法
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數(shù)據(jù)建立索引,mongodb支持二級(jí)索引,為了提高數(shù)據(jù)查找和定位,建立復(fù)合索引是必要的
var animalSchema = new Schema({
name: String,
age: Number,
tags: { age: [String], index: true } // field level
});
animalSchema.index({ name: 1, age: -1 }); // schema level
但是這種索引的建立可能導(dǎo)致顯著的性能影響,建議在生產(chǎn)下停止,將設(shè)置模式下的自動(dòng)索引設(shè)置為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 作為參數(shù),返回單個(gè)文檔。_id //可以是字符串或 ObjectId 對(duì)象。
animalMode.findById(id, function(err, adventure){
if (err) consoel.log(err);
console.log(adventure);
});
//where
//查詢(xún)數(shù)據(jù)類(lèi)型是字符串時(shí),可支持正則
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
官方文檔提供的更新函數(shù)Model.update
Model.update(conditions, doc, [options], [callback])
- conditions 更新條件
- doc 更新內(nèi)容
- option 更新選項(xiàng)
- safe (boolean) 安全模式,默認(rèn)選項(xiàng),值為true
- upsert (boolean) 條件不匹配時(shí)是否創(chuàng)建新文檔,默認(rèn)值為false
- multi (boolean) 是否更新多個(gè)文件,默認(rèn)值為false
- strict (boolean) 嚴(yán)格模式,只更新一條數(shù)據(jù)
- overwrite (boolean) 覆蓋數(shù)據(jù),默認(rèn)為false
- callback
- err 更新數(shù)據(jù)出錯(cuò)時(shí)返回值
- numberAffected (筆者暫時(shí)不清楚)
- rawResponse 受影響的行數(shù)
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);
})
其它
//返回文檔數(shù)
animalMode.count({age: 2}, function(err, cat){
if (err) console.log(err);
console.log(cat);
})
- node.js連接mongoose數(shù)據(jù)庫(kù)方法詳解
- node.js使用mongoose操作數(shù)據(jù)庫(kù)實(shí)現(xiàn)購(gòu)物車(chē)的增、刪、改、查功能示例
- node.js利用mongoose獲取mongodb數(shù)據(jù)的格式化問(wèn)題詳解
- Node.js+jade+mongodb+mongoose實(shí)現(xiàn)爬蟲(chóng)分離入庫(kù)與生成靜態(tài)文件的方法
- Node.js中使用mongoose操作mongodb數(shù)據(jù)庫(kù)的方法
- 安裝使用Mongoose配合Node.js操作MongoDB的基礎(chǔ)教程
- node.js mongoose index索引操作
相關(guān)文章
nodejs使用Express框架寫(xiě)后端接口的全過(guò)程
最近學(xué)習(xí)了基于前后端分離的開(kāi)發(fā)模式,我前端使用Vue框架,后端使用nodejs開(kāi)發(fā)API接口,下面這篇文章主要給大家介紹了關(guān)于nodejs使用Express框架寫(xiě)后端接口的相關(guān)資料,需要的朋友可以參考下2022-05-05
使用Node.js寫(xiě)一個(gè)代碼生成器的方法步驟
這篇文章主要介紹了使用 Node.js 寫(xiě)一個(gè)代碼生成器,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-05-05
詳解node如何將Excel導(dǎo)入數(shù)據(jù)庫(kù)
這篇文章主要為大家詳細(xì)介紹了node如何通過(guò)腳本實(shí)現(xiàn)將Excel導(dǎo)入mysql數(shù)據(jù)庫(kù)里,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2024-11-11
Node 使用express-http-proxy 做api網(wǎng)關(guān)的實(shí)現(xiàn)
這篇文章主要介紹了Node 使用express-http-proxy 做api網(wǎng)關(guān)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
使用node.js半年來(lái)總結(jié)的 10 條經(jīng)驗(yàn)
從3月初來(lái)到帝都某創(chuàng)業(yè)公司的服務(wù)器團(tuán)隊(duì)實(shí)習(xí),到現(xiàn)在已接近半年的時(shí)間。PS: 已轉(zhuǎn)正,服務(wù)器端用的 Node。2014-08-08
詳解nodejs微信公眾號(hào)開(kāi)發(fā)——3.封裝消息響應(yīng)模塊
上一篇文章:nodejs微信公眾號(hào)開(kāi)發(fā)(2)自動(dòng)回復(fù),實(shí)現(xiàn)了簡(jiǎn)單的關(guān)注回復(fù)。采用拼接字符串的形式,并不是很方便,這里我們將其封裝承接口。2017-04-04
使用node搭建自動(dòng)發(fā)圖文微博機(jī)器人的方法
這篇文章主要介紹了使用node搭建自動(dòng)發(fā)圖文微博機(jī)器人的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03

