|
上講主要說了如何配置sails的持久化機(jī)制 ,這講主要說一下實(shí)現(xiàn)持久化時的增刪改查的語法,在sails里使用了和mongodb風(fēng)格類似的waterline查詢語言,使用簡單,語法生動,下面我們主要介紹一下find,findOne,Update,Create,Destory等。 find,查詢并返回結(jié)果集 Model.find({ name: 'foo' })
上面查詢name等于foo的集合,如果希望返回分頁結(jié)果,可以使用limit和skip參數(shù),如下 Model.find({ where: { name: 'foo' }, skip: 20, limit: 10 });
如果希望在結(jié)果中進(jìn)行序列,使用sort參數(shù) Model.find({ where: { name: 'foo' }, skip: 20, limit: 10, sort: 'name DESC' });
下面是包含的實(shí)現(xiàn),類似于C#的,contaions,表示包含某些字符的結(jié)果集 Model.find({ name :
{
'contains' : 'zzl'
}
})
如果希望實(shí)現(xiàn)數(shù)據(jù)庫的枚舉查詢,即in方式,可以這樣進(jìn)行 Model.find({
name : ['Walter', 'Skyler']
});
類似的,not in操作代碼如下 Model.find({
name: { '!' : ['zzl', 'zql'] }
});
當(dāng)進(jìn)行數(shù)據(jù)比較時,可以使用>,<,<=,>=等操作符 Model.find({ age: { '>=': 21 }})
Waterline查詢語言非常強(qiáng)大,幾乎將所有查詢語言的優(yōu)點(diǎn)都收錄了,下面還有startsWith和endsWith,這類似于C#里的方法,“以某些字段開頭或者結(jié)束” Model.find({ city: { 'endsWith': 'china' }})
除了有面向?qū)ο蟮姆椒ㄍ?,還有SQL的,如like方法,實(shí)現(xiàn)了模糊查詢 Model.find({ city: { 'like': '%c%' }})
最后再一下范圍查詢,它實(shí)際上是將多個方法組合在一起使用,下面是查詢在2015-10-1到2015-10-30號的數(shù)據(jù) Model.find({ date: { '>': new Date('10/1/2015'), '<': new Date('10/30/2015') } })
而相對于查詢來說,添加,更新和刪除就簡單多了,下面代碼是對Person表進(jìn)行的操作 添加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);
})
}
|
|
|