Implement Retrieve All Users

Now implement an endpoint that retrieves users from MongoDB.

Add the following service function to src/services/user.service.js.

Mongoose provides find() to retrieve documents matching a query.

For this initial implementation, retrieve all users. Pagination and filtering will be implemented later.

Get All Users Service
export async function getAllUsers() {
  return User.find()
    .select('-password')
    .sort({ createdAt: -1 });
}

Retrieves users, excludes password fields, and sorts the newest users first.

Key Takeaways
  • find() retrieves matching MongoDB documents.

  • select('-password') excludes the password field.

  • sort() controls the order of returned documents.