1. 程式人生 > >node學習篇——mongoose

node學習篇——mongoose

題外話:

   學習mongodb之後,算是瞭解了什麼是非關係型資料庫,然而每個操作時需要一直使用資料庫連線的語句,即使封裝起來也會很繁瑣,因此如果能夠選擇一種驅動來操作mongodb,那node開發的效率及程式碼整潔度會更高。

    正文:

                從資料中瞭解到,通過java三大框架的思路將js的物件與資料庫mongodb產生關係,並持久化。而這也顛覆了自己的資料庫操作,因為學習mongoose之後,根本不需要操作資料庫,也就是說沒有db的寫法。(如果自學估計會一臉懵逼幾天)

             首先,通過http://mongoosejs.com/的官方文件我們可以自己使用hello world。然後就會發現全程都在建立類,例項化類,呼叫類,但是卻是實實在在的出現在了資料庫中。這便是用操作物件的方式操作資料庫。

             接下來,便是mongoose的語法現象。

             1.資料庫連線

              var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test');

              2.定義模型

               var Cat = mongoose.model('Cat', { name: String });

              3.例項化類

               var kitty = new Cat({ name:

'Zildjian' });

              4.類方法的使用

                 kitty.save(function(err) {

if (err) {

console.log(err);

}else {

console.log('meow');

}});

              5.學習mongoose離不開Schema、model的操作                 Schema:指以檔案形式儲存的資料庫模型骨架; model:指定義模型,定義的模型會影響資料庫。 建立Schema

var studentSchema = new mongoose.Schema({

    name     : {type : String},

    age      : {type : Number},

    sex      : {type : String}

});

定義Schema的靜態方法

1.建立靜態方法

studentSchema.statics.find = function(name, callback){

    this.model('Student').find({name: name}, callback);   //this.model('Student')指的是當前這個類

};

2.修改靜態方法

studentSchema.statics.update =function(conditions,update,options,callback){

    this.model("Student").update(conditions, update, options,callback);

}

定義Schema的例項方法

1.建立例項方法

studentSchema.methods.find = function(name, callback){

    this.model('Student').find({name: name}, callback);   //this.model('Student')指的是當前這個類

};

2.修改靜態方法 studentSchema.methods.update =function(conditions,update,options,callback){

    this.model("Student").update(conditions, update, options,callback);

}

定義Schema的靜態方法

1.建立靜態方法

studentSchema.statics.find = function(name, callback){

    this.model('Student').find({name: name}, callback);   //this.model('Student')指的是當前這個類

};

2.修改靜態方法

studentSchema.statics.update =function(conditions,update,options,callback){

    this.model("Student").update(conditions, update, options,callback);

}