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

373
Visualizações
Sort referenced Schema by created at date in Mongoose

following Problem, In my app i have Posts and each post can have an array of comments. I am trying to sort the comments by their date. I already searched for and already tried out any of the solutions but none of them worked for me.

My attempts not working:

const post = await Post.findById(id)
    .populate({
        path: 'comments',
        options: { sort: { createdAt: -1 } },
    })

const post = await Post.findById(id)
        .sort({ 'comments.createdAt': -1 })

In my Post Model if reference the Comments model like following:

COMMENT SCHEMA

    {
        comment: { type: String, required: true },
        user: {
            type: mongoose.Schema.Types.ObjectId,
            required: true,
            ref: 'User',
        },
    },
    { timestamps: true }
)

POST MODEL:

const postSchema = mongoose.Schema(
    {
        user: {
            type: mongoose.Schema.Types.ObjectId,
            required: true,
            ref: 'User',
        },
        image: {
            type: String,
        },
        text: {
            type: String,
            required: true,
        },
        workout: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Workout',
        },
        comments: [commentSchema],
        numComments: {
            type: Number,
            required: true,
            default: 0,
        },
        likes: [likeSchema],
        numLikes: {
            type: Number,
            required: true,
            default: 0,
        },
    },
    {
        timestamps: true,
    }
)

Thx for any help in advance

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The question is where you want to sort happen, to sort it on client side the easiest solution will be in place sorting of array comments, since you are not referencing another schema document with ref there is no need for populate (lookup), just write another then function like this:

    const post = await Post.findById(p._id).then(result => {
        result.comments.sort((a, b) => a.createdAt > b.createdAt ? -1 : 1);
        return result;
    })

To sort while fetching you should use the aggregate model function, and use the pattern of pipe stages: $match, $unwind, $sort, $group. But it is a way complicated.

over 4 years ago · Santiago Trujillo 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