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