Home > Net >  Not able to export function in nodejs
Not able to export function in nodejs

Time:10-30

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

CodePudding user response:

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.

CodePudding user response:

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