Node.js与Sails~中间查询语言Waterline

回到目录

上讲主要说了如何配置sails的持久化机制,这讲主要说一下实现持久化时的增删改查的语法,在sails里使用了和mongodb风格类似的waterline查询语言,使用简单,语法生动,下面我们主要介绍一下find,findOne,Update,Create,Destory等。

find,查询并返回结果集

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

上面查询name等于foo的集合,如果希望返回分页结果,可以使用limit和skip参数,如下

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

如果希望在结果中进行序列,使用sort参数

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

下面是包含的实现,类似于C#的,contaions,表示包含某些字符的结果集

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

如果希望实现数据库的枚举查询,即in方式,可以这样进行

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

类似的,not in操作代码如下

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

当进行数据比较时,可以使用>,<,<=,>=等操作符

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

Waterline查询语言非常强大,几乎将所有查询语言的优点都收录了,下面还有startsWith和endsWith,这类似于C#里的方法,“以某些字段开头或者结束”

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

    }

回到目录

posted @ 2015-10-19 10:37  张占岭  阅读(4987)  评论(2编辑  收藏  举报