0

I am trying to sort a collection with React and MongoDB to have the newest comments on top. I have a database model Employee and inside an array of comment objects like so comments[commentsSchema].

I'd like to get those comments sorted.

This is my model :

import mongoose from 'mongoose';

const commentsSchema = new mongoose.Schema(
    {
        userName: { type: String, required: true },
        comment: { type: String, required: true },
    },
    {
        timestamps: true,
    }
);

const employeeSchema = new mongoose.Schema(
    {
        userName: { type: String, required: true },
        email: { type: String, required: true, unique: true },
        firstName: { type: String, required: true },
        lastName: { type: String, required: true },
        address: { type: String, required: true },
        slug: { type: String, required: true, unique: true },
        role: { type: String, required: true },
        comments: [commentsSchema],
    },
    {
        timestamps: true,
    }
);

const Employee = mongoose.model('Employee', employeeSchema);
export default Employee;
  

and this is my router:

userRouter.get('/slug/:slug', isAuth, async (req, res) => {
    const employee = await Employee.findOne({ slug:
        req.params.slug,
    });

    if (employee) {
        res.send(employee);
    } else {
        res.status(404).send({ message: 'Employee Not Found' });
    }
});

Employee Collection, Comments Array inside, Comment Objects inside Array. Each Object in Array is each Comment:

id: ObjcetId(6367fd80c6c9b16f4e7dd9cc)
userName: testName
email: testEmail
adress: testAddress
comments: Array
  0: Object
  1: Object
  2: Object   
createdAt: 2022-11... 

      0: Object
         userName: 
         comment:
         _id:
         createdAt:
    
      1: Object
         userName: 
         comment:
         _id:
         createdAt:

      2: Object
         userName: 
         comment:
         _id:
         createdAt:

     
 So I am trying to show Object 2 as Firts, because it is the 
 newest Comment 

 

1 Answers1

0

The simplest way to do this is to sort the comments after retrieving the data.

userRouter.get('/slug/:slug', isAuth, async (req, res) => {
    const employee = await Employee.findOne({ slug:
        req.params.slug,
    });

    // Sort comments by createdAt
    employee.comments.sort((a,b) => b.createdAt - a.createdAt);

    if (employee) {
        res.send(employee);
    } else {
        res.status(404).send({ message: 'Employee Not Found' });
    }
});
Nir Levy
  • 4,613
  • 2
  • 34
  • 47