RinMori
RinMori

Reputation: 61

TypeError: connectDb is not a function?

I am new to express and node while I connecting mongodb from mongoose to localhost I get an error like TypeError: connectDb is not a function?

src/models/index

const mongoose = require("mongoose");

const User = require("./user");
const Message = require("./message");

const connectDb = () =>
  mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true });

const models = { User, Message };

exports = { connectDb };
module.exports = models;

src/index

// .... Some code here

const { connectDb } = require("./models");

// .... Some code here

connectDb()
  .then(async () => {
    app.listen(process.env.PORT);
  })
  .catch(error => console.error(error));

Upvotes: 2

Views: 4537

Answers (2)

Yousaf
Yousaf

Reputation: 29282

exports = { connectDb };

this statement is not correct. Its not exporting the connectDb function.

if you want to use exports keyword to export connectDb function, you have to do it as

exports.connectDb = () => mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true });

or simply

exports.connectDb = connectDb;

If you want to export multiple things, you can add multiple properties to exports object

to export models, you can do

exports.models = models;

Now this file will export an object that has two properties on it, connectDb and models

Another way to export multiple things is

module.exports = {
    connectDb,
    models
};

this will also export an object containing two properties, connectDb and models

Upvotes: 2

Marcos Luis Delgado
Marcos Luis Delgado

Reputation: 1429

You are actually doing a weird thing. exports variable is set to point to module.exports, so when u change its reference by doing exports = { connectDb } you are actually breaking that variable's reference, so it's not exporting anything. Next thing u do is exporting ur models, which is correct, but your connectDb is actually not being exported, so you can not use it in your second file. I guess you want to export both, so actually there are some ways to achieve that. Here you have two valid options, first one using the spread operator with module.exports and second one using exports and not changing its reference but it's properties, so it keeps working correctly:

module.exports  = {
  ...models,
  connectDb
}
exports.connectDb = connectDb
exports.User = User
exports.Message = Message

Upvotes: 2

Related Questions