Home > Software engineering >  Exporting Mongoose connection to a different file
Exporting Mongoose connection to a different file

Time:01-10

Current file/folder structure:

Part 1 - Create a mongoose connection

path: myApp/src/db/mongoose.js

import mongoose from "mongoose";

mongoose.set("strictQuery", true);

mongoose.connect("mongodb://localhost:27017/task-manager-api", { useNewUrlParser: true }, () => {
  console.log("connected to database");
});

module.exports = mongoose; //this is redundant without assigning to a variable

Part 2 - Importing it in a file where I run express path: myapp/index.js

import express from "express";
import "./src/db/mongoose";

const app = express();
const port = 3000;

app.use(express.json());

app.listen(port, () => {
  console.log("listening on port 3000");
});

Error: Cannot find module "myApp/src/db/mongoose" imported from "myApp/index"

Here's what I have tried:

  1. I tried to use const mongoose = require("mongoose") and then module.exports = mongoose to move the connection to the index.js file but still no luck
  2. A tonne of google search to find if a separate mongoose connection file is maintained anywhere
  3. I looked up how to use require module in ES6 but still no luck
// import { createRequire } from "module";
// const require = createRequire(import.meta.url);

Any help/advice would be highly appreciated. Thank you.

Expected output:

  1. Mongoose connection imported into index.js

CodePudding user response:

I'd look at doing something along the lines of

  • wrapping your mongoose connect up in an exported function
  • Import the connect function in your index.js and call it

The code may end up looking like this (Not tested!): mongoose.js:

export const connect = async () => {
    await mongoose.connect("mongodb://localhost:27017/task-manager-api", {
        useNewUrlParser: true
    });
};

index.js


import express from "express";
import {connect} from "<...relevant_path_here...>/mongoose";

const app = express();
const port = 3000;

app.use(express.json());

const start = async () => {
  try {
    await connect();
    app.listen(port, () => {
        console.log("listening on port 3000");
    });
  } catch (error) {
    console.error(error);
    process.exit(1);
  }
};

start();
  • Related