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

79
Visualizações
Trouble moving Express Controller logic to a Service Class

There is a User Controller that handles a GET request to /user/ and returns an array of two JSON objects pulled randomly from a collection in MongoDB.

Here is the response that is sent back (works inside controller):

[{
    "name": "User 1",
    "pet_name": "Bob 1"
},
{
    "name": "User 2",
    "pet_name": "Bob 2"
}]

I wanted to move the logic of getting information from a DB to a service class (e.g. UserService.js) so the controller handles only the request and passes it along.

I copied the exact code and put it into a function inside of the UserService class. But when I execute the method in the class, it ends up not returning anything.

user.controller.js

const UserService = require("../services/UserService");

async function getUser(req, res) {
    const result = await UserService.getRandomUsers();
    return res.status(200).json(result);
}

module.exports = {
    getUser
}

UserService.js

const User = require("../models/User");

class UserService {
    async getRandomUsers() {
        const count = await User.count();

        const rand1 = Math.floor(Math.random() * count);
        const rand2 = Math.floor(Math.random() * count);

        await User.findOne().skip(rand1).then(result1 => {
            
            let results = [];

            let user1 = new Object();
            user1.name = result1.name;
            user1.pet_name = result1.pet_name;

            results.push(user1);

            User.findOne().skip(rand2).then(result2 => {
            
                let user2 = new Object();

                user2.name = result2.name;
                user2.pet_name = result2.pet_name;

                results.push(user2);
                
                return results;
        
            });

        });
    }
}

module.exports = new UserService();

What is the Problem?

Besides the return res.status(200).json(results) being changed to return results inside of the new class. It doesn't return anything when I run the GET request to /user/.

When I log the results to console at the end of the class method getRandomUser(), it outputs the "results" that contain two random users in an array (as shown in the expected response). But when the controller return's the response with the results, there isn't anything there. I'm confused on the reason the GET request is returning nothing (or undefined?). Please help.

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

0

Method getRandomUsers() doesn't return anything, you need to add some return statements like this:

    async getRandomUsers() {
        const count = await User.count();

        const rand1 = Math.floor(Math.random() * count);
        const rand2 = Math.floor(Math.random() * count);

        return await User.findOne().skip(rand1).then(result1 => {
            
            let results = [];

            let user1 = new Object();
            user1.name = result1.name;
            user1.pet_name = result1.pet_name;

            results.push(user1);

            return User.findOne().skip(rand2).then(result2 => {
            
                let user2 = new Object();

                user2.name = result2.name;
                user2.pet_name = result2.pet_name;

                results.push(user2);
                
                return results;
        
            });

        });
    }
about 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