Here’s the user story:
You can add from
, to
and limit
parameters to a /api/users/:_id/logs
request to retrieve part of the log of any user. from
and to
are dates in yyyy-mm-dd
format. limit
is an integer of how many logs to send back.
I know I can request the entire document and then compose the response using POJO. However, as a learning experience, I would love to filter
the query
and receive only the information required per the user story. This would involve filtering by date (from/to) and limiting the number of logs received.
For context, here’s a simplified version of the Schema
. Note that the date
key is part of a nested object in the log
array.
const UserSchema = new mongoose.Schema({
username: String,
log: [
{
description: String,
duration: Number,
date: Date
}
]
})
module.exports = mongoose.model('User', UserSchema)
Here’s the query that’s giving me a hard time. I have tried many combinations of this idea after reading the Mongoose and Mongo documentation, a popular CodeBarbarian article and many, many more sources. Getting a single document by _id
is trivial, but I never imagined it would be so hard to filter
the query aggregating other parameters.
const UserModel = require('../models/user.model.js');
router.get('/api/users/:_id/logs', (req, res) => {
/*error handling*/
const _id = req.params._id
const { from, to, limit } = req.query
UserModel.findOne({ _id: _id })
.where({ log: { date: { $gte: new Date(from), $lte: new Date(to) } } })
.select({log: {$slice:limit}})
.exec(/*callback*/)
/* response */
})
Here’s yet another idea I tried based on a MongoDB documentation example.
UserModel.findOne({_id: _id}, { log:{ date:{$gte: new Date(from), $lte: new Date(to)} } } )
I’ve also tried this notation:
UserModel.where(log.date).gte(new Date(from)).lte(new Date(to))
.where("log").slice(+limit)
.exec(/*callback*/)
Thank you very much if you’ve read this much, and I would greatly welcome any help. I’m developing locally and testing with Insomnia, and can deploy to Repl or Glitch if necessary, but I’d have to be at the computer to start the server for live testing.
Challenge: Exercise Tracker
Link to the challenge: