I'm currently able to successfully fetch data from my database, create an index, and then get the most recent 7 records using pouchDB in a react.js progressive web app.
My hurdle currently is querying by dates. So with my current code, I'm getting all data, creating an index and then I'm getting only the 7 latest records so that I can map the data. But I'm trying to figure out how to use my moment date for the current day: newestDate: moment(this.currentDate).format("YYYY-MM-DD")
and use this to say "get the most recent record from each day over the last 7 days"
So effectively, I have records which have the format of {caloriesBurned:"250", caloriesConsumed:"1450", createdAt:"2020-03-05"}
and I want to be able to modify my query to get only one record for each day, starting today and going back for 7 days
How can I properly do this in pouchDB with this code:
fetchData = () => {
this.setState({
calorieElements: null,
});
this.state.caloriesDB.db.allDocs({
include_docs: true,
}).then(result => {
const rows = result.rows;
console.log('this is a row');
console.log(result);
this.setState({
calorieElements: rows.map(row => row.doc),
});
console.log(this.state.calorieElements);
}).catch((err) =>{
console.log(err);
});
}
getMax = () => {
this.state.caloriesDB.db.createIndex({
index: {
fields: ['_id','caloriesBurned', 'createdAt']
}
}).then(result => {
console.log(result);
this.setMax();
}).catch((err) =>{
console.log(err);
});
}
setMax = () => {
this.state.caloriesDB.db.find({
selector: {
$and: [
{_id: {"$gte": null}},
{caloriesBurned: {$exists: true}},
{caloriesConsumed: {$exists: true}},
{createdAt: {$exists: true}}
]
},
fields: ['caloriesBurned','caloriesConsumed', 'createdAt'],
sort: [{'_id':'desc'}],
limit: 7
}).then(result => {
const newDocs = result.docs;
const docCalories = newDocs.map(x => +x.caloriesConsumed - +x.caloriesBurned);
}).catch((err) =>{
console.log(err);
});
}