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);

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章