类似MongoDB的JS库在客户端indexedDB中存储对象?

时间:2018-02-20 17:09:55

标签: javascript mongodb minimongo

给出以下localStorage代码(jsfiddle):

// my new information
var data = {character: "中", totalMistakes: 0};
var han  = data.character;

// create localStorage; Unpack, update, repackage knol
/* **** THIS IS THE SECTION TO CONVERT  **** */
localStorage.knol = '{}'; // create pseudo object, as string
var knol = JSON.parse(localStorage.knol)
knol[han] = data;
localStorage.knol = JSON.stringify(knol);

// Print to check if all went well.
console.log('data: ',data)
console.log('han: ',han)
console.log('knol: ',knol)
console.log('localStorage.knol: ',localStorage.knol)
console.log('localStorage.knol: ',JSON.parse(localStorage.knol))
console.log('localStorage.knol[han]: ',JSON.parse(localStorage.knol)[han])

最后,localStorage.knol是:

{
  "中": {character: "中", totalMistakes: 0}
}

我正在寻找类似Mongo的js库来存储客户端indexedDB上的数据,其语法类似于我已经熟悉的MongoDB。

如何将上面的localStorage代码转换为类似Mongo的IndexedDB库语法,以便存储对象?

编辑:我建议使用minimongo,但任何存储在indexedDB中的类似MongoDB的库都可以。

1 个答案:

答案 0 :(得分:1)

a variety of librairies available to do that

Dexie.js

使用Dexie.js and its APIjsfiddle):

<!-- Include dexie.js -->
<script src="https://unpkg.com/dexie@latest/dist/dexie.js"></script>
<script>
var db = new Dexie('MyDatabase');

// Define a schema
db.version(1).stores({ knol: 'character, totalMistakes' });

// Open the database
db.open().catch(function(error) { alert('Uh oh : ' + error); });

// or make a new one
db.knol.put({ character: '中', totalMistakes: 8 });

// Find some old friends
var mistakes = db.knol.where('totalMistakes');
//mistakes.above(6).each (function (item) { console.log (item); });
mistakes.aboveOrEqual(0).each (function (item) { console.log (item)});
</script>

Minimongo

我不推荐它,但是there is how to use it in web browsers

ZangoDB

(正在进行的探索https://jsfiddle.net/vb92pecv/3/