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

    }

回到目录

相关文章
相关标签/搜索