Node.js的MongoDB驅動Mongoose基本使用教程_node.js

來源:互聯網
上載者:User

使用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}});

自訂方法

可以為SchemaBinder 方法

 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

//findanimalMode.find(function(err, cat){ if (err) console.log(err); console.log(cat);})//findOneanimalMode.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) strict 模式,只更新一條資料
  • 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);})

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.