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

201
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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