Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

370
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda