PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 27, 2022

[FIXED] how to pass correctly a module in node

 November 27, 2022     architecture, javascript, module, node.js, optimization     No comments   

Issue

app.js --------------

const mongoose = require("mongoose");
const utils = require("./config/utils");
const app = express();

utils.initializeDb(mongoose);
app.listen(3000);

config/utils.js

module.exports = (mongoose) => {
  initializeDb: async () => {
    await mongoose.connect(
      process.env.MONGO_URI,
      {
        useNewUrlParser: true,
      },
      () => {
        console.log("Mongoose connection successfuly started");
      }
    );
  };
};

The error in the terminal/console is: TypeError: utils.initializeDb is not a function.

I'm digging into optimization, encapsulation, to clean more my code passing modules through functions and etc. and I tried this thing but it give me this error... I would like to know the error that is happening in the code and also some tips on how to optimize this code. Thank you :)


Solution

try the below method :

app.js

    const mongoose = require("mongoose");
    const initializeDb = require("./config/utils");
    const app = express();

    initializeDb(mongoose);
    app.listen(3000);

config/utils.js

module.exports = {
  initializeDb: async (mongoose) => {
    await mongoose.connect(
      process.env.MONGO_URI,
      {
        useNewUrlParser: true,
      },
      () => {
        console.log("Mongoose connection successfuly started");
      }
    );
  };
};


Answered By - Critical Carpet
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing