Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!