I have encountered an issue while attempting to send 3 separate updateMany requests within a get request, each using a different query. While the first two requests work perfectly, the third updateMany request only functions as expected after refreshing the page twice.
Below is the code I am currently using:
app.get('/', (req, res) => {
let todaysDate = new Date().toString().split(' ').slice(0, 4).join(' ')
let todaysDateMs = new Date(todaysDate + ', 00:00:00').getTime()
habitsCollection.updateMany({}, {
$set: {
todaysDate,
todaysDateMs
}
}).then(res => {
habitsCollection.updateMany({ lastClicked: { $ne: todaysDate } }, {
$set: {
clicked: 'false'
}
}).then(res => {
habitsCollection.updateMany({ $expr: { $gte: [{ $subtract: ["$todaysDateMs", "$lastClickedMs"] }, 172800000] } }, {
$set: {
streak: 0
},
})
})
})
habitsCollection.find({}).toArray()
.then(results => {
console.log(results)
let filtered = results.filter(result => result.clicked === 'false')
habitsLeft = filtered.length
res.render('index.ejs', { habits: results, dayVar: 'days', habitsLeft })
})
})
My expectation was that on every page load, if a document contains a lastClickedMs key/value subtracted from todaysDateMs key/value which is greater than or equal to 172800000, then the streak value should be reset to 0. This functionality does occur but only after loading the page for the second time.