Node.js與Sails~中間查詢語言Waterline

回到目錄html

上講主要說了如何配置sails的持久化機制,這講主要說一下實現持久化時的增刪改查的語法,在sails裏使用了和mongodb風格相似的waterline查詢語言,使用簡單,語法生動,下面咱們主要介紹一下find,findOne,Update,Create,Destory等。mongodb

find,查詢並返回結果集數據庫

Model.find({ name: 'foo' })

上面查詢name等於foo的集合,若是但願返回分頁結果,能夠使用limit和skip參數,以下spa

Model.find({ where: { name: 'foo' }, skip: 20, limit: 10 });

若是但願在結果中進行序列,使用sort參數code

Model.find({ where: { name: 'foo' }, skip: 20, limit: 10, sort: 'name DESC' });

下面是包含的實現,相似於C#的,contaions,表示包含某些字符的結果集htm

Model.find({  name : 
{
    'contains' : 'zzl'
  }
})

若是但願實現數據庫的枚舉查詢,即in方式,能夠這樣進行對象

Model.find({
  name : ['Walter', 'Skyler']
});

相似的,not in操做代碼以下blog

Model.find({
  name: { '!' : ['zzl', 'zql'] }
});

當進行數據比較時,能夠使用>,<,<=,>=等操做符ip

Model.find({ age: { '>=': 21 }})

Waterline查詢語言很是強大,幾乎將全部查詢語言的優勢都收錄了,下面還有startsWith和endsWith,這相似於C#裏的方法,「以某些字段開頭或者結束」ci

Model.find({ city: { 'endsWith': 'china' }})

除了有面向對象的方法外,還有SQL的,如like方法,實現了模糊查詢

Model.find({ city: { 'like': '%c%' }})

最後再一下範圍查詢,它其實是將多個方法組合在一塊兒使用,下面是查詢在2015-10-1到2015-10-30號的數據

Model.find({ date: { '>': new Date('10/1/2015'), '<': new Date('10/30/2015') } })

而相對於查詢來講,添加,更新和刪除就簡單多了,下面代碼是對Person表進行的操做

添加

 addUser: function (param,cb) {
        var opt = param || { name: 'zzl' };

        Person.create(opt).exec(function (err, record) {

            console.log("添加")
            if (err) {
                cb('ERROR_DATABASE_EXCEPTION');//輸出錯誤
            } else {

                cb(null, record);//正確返回
            }
        });
    }

 更新

  modify:function(id,param,cb){
        var opt = param || { name: 'zzl' };
        Person.update({id:id},opt,function(err,record){
            console.log("修改")
            if (err) {
                cb('ERROR_DATABASE_EXCEPTION');//輸出錯誤
            }else{

                cb(null, record);//正確返回
            }

        });
    }

刪除

  delete:function(id,cb){
        Person.destroy({id:id}).exec(function(err){
            console.log("刪除,ID:"+id);
            cb(null);
        })

    }

回到目錄

相關文章
相關標籤/搜索