Reputation: 1386
I have a CouchDB document that I want to output ordered by "date"
:
{
"_id": "accounts",
"accounts": [
{
"name": "_name.1",
"date": 1524336565172
},
{
"name": "_name.2",
"date": 1524336565173
},
{
"name": "_name.3",
"date": 1524336565171
}
}
Right now I'm using the following PouchDB, which populates a <ul>
, but obviously not in the correct order:
localDB.get('accounts').then(function(result){
$.each(result.accounts, function(i, value) {
$('ul').append('<li data-date="' + value.date + '">' + value.name + '</li>');
});
});
The output I am looking for is:
<li data-date="1524336565171">_name.3</li>
<li data-date="1524336565172">_name.1</li>
<li data-date="1524336565173">_name.2</li>
Thanks in advance! :)
Upvotes: 1
Views: 96
Reputation: 7989
CouchDB indexing works if you have multiple documents and you intend to sort docs based on document fields. You have a single document, therefore you cannot use CouchDB indexing and you have to sort the fields in your code logic.
It might be more practical to have mulitple documents, rather than keeping all your data inside just a single document.
You can breakup your single document, into multiple documents like this:
{
"_id": "account 001",
"name": "_name.1",
"date": 1524336565172
}
{
"_id": "account 002",
"name": "_name.2",
"date": 1524336565173
}
{
"_id": "account 003",
"name": "_name.3",
"date": 1524336565171
}
Then you can create a view function in CouchDB and get documents indexed/sorted by the date
field like below:
function (doc) {
if(doc.date && doc.name){
emit(doc.date, doc.name);
}
}
The above view can be created with PouchDB. You can use Map/reduce queries or you can use Mango queries.
Upvotes: 1
Reputation: 1537
While @user3405291's answer is generally considered better practice, you could also keep your existing document structure and create a view from your single accounts document:
function (doc) {
if(doc.accounts) {
doc.accounts.forEach(function(account) {
emit(account.date, account.name);
});
}
}
For storing accounts, I'd strongly recommend using a document per account as proposed by the other answer, though. It's much easier to scale, because accounts can then be updated/deleted independently.
Upvotes: 1