i'm very new at node.js, javascript, etc. so i have no experience. I am having a problem when trying to get a return value from a helper function in my controller. The helper function intends to get a value from a mongodb database and return it to the main controller. But when i call the helper function i get undefined as result. I put a console.log inside the helper function and the data from the db is being retrieved correctly. Please Help. This is my controller code.
var validator = require("validator");
var Necesidad = require("../models/necesidad");
var NecesidadCategoria = require("../models/necesidad_categoria");
var helpers = require("../controllers/helpers/index.js");
const necesidad_categoria = require("../models/necesidad_categoria");
var controller = {
new: (req, res) => {
var params = req.body;
try {
var validateNombre = !validator.isEmpty(params.nombre);
var validateCantidad = params.cantidad >= 0;
if (validateNombre && validateCantidad) {
var necesidad = new Necesidad();
necesidad.nece_nombre = params.nombre;
necesidad.nece_cantidad = params.cantidad;
necesidad.nece_estado = 0;
necesidad.nece_imagen = "";
var args = { cat_nombre: params.cat_nombre };
var categoria = helpers.getNecesidadCategoria(args);
console.log("categoria: " + categoria);
necesidad.save((err, necesidadStored) => {
if (err || !necesidadStored) {
return res.status(404).send({
status: "error",
message: "Los datos no fueron guardados: " + err,
});
}
return res.status(200).send({
status: "success",
necesidad: necesidadStored,
});
});
} else {
return res.status(200).send({
status: "error",
message: "Error de validación de datos.",
});
}
} catch (err) {
return res.status(200).send({
status: "error",
message: "Error de validación de datos. Traza completa: " + err,
});
}
},
};
module.exports = controller;
And this is my helper function:
var validator = require("validator");
var NecesidadCategoria = require("/ProyectosAngular/SeminarioFinalBackend/models/necesidad_categoria");
module.exports = {
getNecesidadCategoria: function (args) {
var nombre = args.cat_nombre;
var nombreValidation = !validator.isEmpty(nombre);
if (nombreValidation) {
NecesidadCategoria.findOne(
{ cat_nombre: nombre },
function (err, necesidad_categoria) {
if (err || !necesidad_categoria) {
return null;
} else {
console.log("categoria function:" + necesidad_categoria);
return necesidad_categoria;
}
}
);
}
},
};