Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda