【问题标题】:How to retrieve a sorted list of objects in ydn-db?如何在 ydn-db 中检索对象的排序列表?
【发布时间】:2013-09-27 02:42:13
【问题描述】:

按照此处http://dev.yathit.com/ydn-db/getting-started.html 的文档中的示例,“排序”下的第一个示例。

我的代码:

var schema = {
  stores: [
    {
      name: "authors",
      keyPath: "id",
      indexes: [
        { keyPath: "born" }
      ]
    }
  ]
};
var db = new ydn.db.Storage("library", schema);

db.put("authors", [{ id: "111", born: "zzz" }, { id: "555", born: "bbb" }, { id: "999", born: "aaa" }]).done(function() {
  // query with default ordering
  db.values("authors").done(function(r) {
    console.log("A list of objects as expected", r);
  });

  // query by ordered by "born" field
  db.values(new ydn.db.Cursors("authors", "born", null, false)).done(function(r) {
    console.log("This is a list of ids, not objects", r);
  });
});

将查询从默认排序更改为按特定列排序似乎会将其行为从返回对象列表更改为仅返回 ID 列表。难道我做错了什么?如何获取对象列表?

【问题讨论】:

    标签: javascript indexeddb ydn-db


    【解决方案1】:

    应该是

    // query by ordered by "born" field
    db.values(new ydn.db.IndexValueCursors("authors", "born", null, false)).done(function(r) {
      console.log("list of objects sorted by born", r);
    });
    

    // query by ordered by "born" field
    db.values("authors", "born", null, false).done(function(r) {
      console.log("list of objects sorted by born", r);
    });
    

    或者干脆

    db.values("authors", "born").done(function(r) {
      console.log("list of objects sorted by born", r);
     });
    

    一个好的 API 应该很容易地完成这些常见的查询,而无需阅读文档。我会认为更好的API。现在,您必须阅读迭代器的工作原理:http://dev.yathit.com/api-reference/ydn-db/iterator.htmlydn.db.Cursors 的参考值是主键。因此 values 返回列表主键。而ydn.db.IndexValueCursors 的参考值为 记录值,所以values 返回对象列表。事实上,这些就是 IndexedDB API 的工作原理。

    还有一点就是上面两个查询有不同的性能特点。第二种方法,直接查询比第一种方法更快,使用迭代器。这是因为,迭代器将进行迭代,而第二种方法将使用批量查询。由于不支持迭代,websql 的性能差异很大。

    【讨论】:

    • 感谢您的实质性回答。第三个工作正常,第二个也可以,但我不得不将其更改为 var limit = 999; db.values("authors", "born", null, limit).done(...);否则我得到“ydn.error.ArgumentException: limit must be a number.”
    猜你喜欢
    • 2014-04-29
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 2015-02-14
    • 2015-03-31
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    相关资源
    最近更新 更多