2013-09-27 30 views
1

以下是文档http://dev.yathit.com/ydn-db/getting-started.html中的示例,这是“排序”下的第一个示例。如何检索ydn-db中的对象的排序列表?

我的代码:

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列表。难道我做错了什么?如何获取对象列表?

回答

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.html参考值ydn.db.Cursors是主键。这就是为什么 values返回列表主键。而ydn.db.IndexValueCursors的参考值是 的记录值,所以values返回对象列表。实际上,这些是IndexedDB API的工作原理。

另一点是以上两个查询有不同的性能特征。第二种方法,直接查询比使用迭代器的第一种方法快。这是因为迭代器会迭代,而第二种方法将使用批量查询。由于不支持迭代,因此websql的性能差别很大。

+1

感谢您的实质性答案。第三个工作正常,第二个也是,但我不得不将其更改为 var limit = 999; db.values(“authors”,“born”,null,limit).done(...); 否则我得到“ydn.error.ArgumentException:限制必须是一个数字。” –