I have saved date as a String in exercise schema which saved as a array in user schema . and my schema as follows.
const exerciseSchema = new Schema({
description: String,
duration: Number,
date: String
});
const Exercise = mongoose.model("Exercise", exerciseSchema);
const userSchema = new Schema({
username: { type: String, unique: true },
log: [exerciseSchema]
});
const User = mongoose.model("User", userSchema);
I need to call their data, according to queries i use for sort by dates. and i have done it as below.
app.get("/api/users/:_id/logs", (request, response) => {
let _id = request.params._id;
let query = request.query;
User.findById(_id, (error, result) => {
if(!error){
let responseObject = result
if(query.from || query.to){
let fromDate = new Date(0)
let toDate = new Date()
if(query.from){
fromDate = new Date(query.from)
}
if(request.query.to){
toDate = new Date(query.to)
}
fromDate = fromDate.getTime()
toDate = toDate.getTime()
responseObject.log = responseObject.log.filter((session) => {
let sessionDate = new Date(session.date).getTime()
return sessionDate >= fromDate && sessionDate <= toDate
})
}
if(query.limit){
responseObject.log = responseObject.log.slice(0, query.limit)
}
responseObject = responseObject.toJSON()
responseObject['count'] = result.log.length
response.json(responseObject)
}
})
});
only thing i need to follow is which I can't get the date in locale format. the date is saving as ISO format(2015-12-15). I need to call it in locale format. but in here i have no access to the objects of log array. I have no idea why.??
Don't store your dates as strings. Store your dates as Mongo dates (ISODate("2020-12-24T05:00:00.000Z")). So you can query Mongo by date directly. Transform your dates afterwards in whatever format you want.
Now Mongoose is weird. By default, it returns an array of Mongoose objects, which are immutable and hard to work with. If you need only pure JSON data, add the option { lean : true }, or .lean() if you work with the chainable syntax (like below).
app.get("/api/users/:_id/logs", async (request, response) => {
let _id = request.params._id;
let query = request.query;
let user;
try {
user = await User
.findById(_id)
.populate("log")
.lean() // Returns JSON, not immutable Mongoose objects
.exec(); // Returns a Promise so you can 'await' it
} catch (error) {
response.json(error); // catch your errors
return;
}
if (query.from || query.to) {
let fromDate = new Date(0)
let toDate = new Date()
if (query.from) {
fromDate = new Date(query.from)
}
if (request.query.to) {
toDate = new Date(query.to)
}
const fromDateN = fromDate.getTime()
const toDateN = toDate.getTime()
user.log = user.log.filter((session) => {
let sessionDate = new Date(session.date).getTime();
return sessionDate >= fromDateN && sessionDate <= toDateN;
})
}
if (query.limit) {
user.log = user.log.slice(0, query.limit)
}
// user = user.toJSON() --> It's already JSON now.
user['count'] = user.log.length
response.json(user)
});