对localStorage操作的封装:StoreDB

jopen 9年前

StoreDB是一个基于localStorage的本地储存库,通过模拟MongoDB的一些API和概念(如“集(collection)”和“文档(document)”),弥补了原生localStorage的多处不足,大大增强了localStorage的功能。

Why StoreDB?

  • StoreDB使你在无须配置数据库的情况下,在静态页面中也能实现大量数据储存和交互。这意味着你能用StoreDB非常简便地建立一个功能强大的SPA(单页面应用,Single Page Application)。

  • StoreDB也适用于demo产品的开发。比如,假定你正在参加编程马拉松,你的团队只不过是想做出一个用以展示的demo,却不得不花费时间在远程或本地架设server,再配置数据库,白白浪费了宝贵的时间。使用StoreDB,你只需嵌入一段javascript代码就能实现丰富的数据交互。

  • 使用AngularJS配合StoreDB更是如虎添翼。

Quick Start

插入(Insert)

向名为players的集合中插入一条文档:

storedb('players').insert({"name":"Randy","sex":"male","score":20},function(err,result){    if(!err){      //do sth...    } else //do sth...  })

查询(Find)

查询players集合中nameRandy的文档:

storedb('players').find({"name":"Randy"},function(err,result){    if(!err){      //use result to do sth...    } else //do sth...  })

如果需要查询集合中所有文档,将参数设置为空即可:

storedb('players').find() 

函数将返回一个数组类型。

更新(Update)

players集合中nameRandyscore增加10

storedb('players').update({"name":"Randy"},{"$inc":{"score":"10"}},function(err){    if(!err){      //do sth...    } else //do sth...  })

你可能已经注意到,StoreDB拥有和MongoDB一样的修改器!关于修改器类型请查看API

如果修改器为空,则默认为$set修改器:

storedb('players').update({"name":"Randy"}, {"sex":"male","name":"kriss"}) 

删除(Remove)

删除在players集合中nameRandy的一条文档:

storedb('players').remove({"name":"Randy"},function(err){    if(!err){      //do sth...    } else //do sth...  })

如果要把整个集合删除,把参数设置为空:

storedb('players').remove() 

项目主页:http://www.open-open.com/lib/view/home/1413638829372