Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
Not able to export function in nodejs

I have defined a function service in one of the file

import Category from '../models/Category.js';

export const AllCategories = () => {
        console.log('hit');
        const cursor =  Category.find({});
        console.log(cursor);
        return cursor
}


export default {AllCategories}

I am importing this in the controller file

import express from 'express';
import categoryService from '../services/categories.js'
const router = express.Router();

export const getCategories = async(req,res) => {
    try {
        const categoriesInfo = categoryService.AllCategories
        res.status(200).json(categoriesInfo)
    } catch (error) {
        res.status(404).json({ message: error.message });
    }
}

export default router;

But the issue is that AllCategories is not getting run, what is wrong here

I also tried adding async/await

import Category from '../models/Category.js';

export const AllCategories = async () => {
    try {
        console.log("hit");
        const cursor =  await Category.find({});
        console.log(cursor);
        return cursor
    } catch (error) {
       return error 
    }
}


export default {AllCategories}

But still no luck

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You're not calling the function, this saves it in the variable categoriesInfo:

const categoriesInfo = categoryService.AllCategories

To get its return value:

const categoriesInfo = await categoryService.AllCategories();

Note: I think you need to make it async if you're doing a db transaction so keep the second version and test it.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can't use the ES module or ESM syntax by default in node.js. You either have to use CommonJS syntax or you have to do 1 of the following.

  1. Change the file extension from .js to .mjs
  2. Add to the nearest package.json file a field called type with a value of module
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda