Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
I cannot return the date in locale string format of a mongodb schema which is in another schema

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.??

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!