I'm designing a quiz app with Angular and Ionic. I have about 2000 questions in json format and I choose PouchDB as database. CouchDB is perfect for me: I can add new question on a server and app auto update question and answer.
But I have a doubt now: I cannot find a way to get random docs from Pouch. With my app I will generate quizzes from some selected section and I must get a variable number of docs from my DB.
I'm using the db.allDocs([options], [callback]) api, I can set a limit but I cannot find a way to get random doc.
Is there any solution?
The first solution given by @nlawson isn't always working, for example I had to delete every document fetched so I lose the sequence of IDs, for example:
I had a list of documents with ids from 1 to 5
1- random is 3
2- get document with id 3
3- delete document with id 3 State of the database [1,2,4,5]
4- if random is anything but 3 repeat steps above, but if random is 3 or any id already deleted it cause problems, so this solution wasn't working, so I found another solution which is:
ANSWER:
Using the Mango querie find(), with this code
let rand = Math.floor(Math.random() * (max - min + 1)) + min;
db.find({
selector: {_id: {$gte : '1'}},
limit : 1,
skip : rand-1,
});
First of all I get a random number, the max is the number of documents in my database and the min is 1 as the first id given to the first document.
After that I execute the find() query to select documents with an id great or equal to 1 (basically all), limit the query to retrieve only the first and start retrieving from rand-1.
To reuse our first example with rand equal 3 it will be something like that:
1- get all documents with an ID great or equal 1 => [1,2,3,4,5]
2- starting from rand-1 witch is 3-1=2 get the a limited number of documents the limit is 1 => [2]
So it will always return the document on the position rand.
P.S: to use find() you must install on top of pouch this library pouchdb.find.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With