Home > Software engineering >  Import mongoose file in node app using ES6 syntax
Import mongoose file in node app using ES6 syntax

Time:12-23

I am currently learning mongoose with Node.js. I have a connection string in mongoose.js file. I want it to connect to database when I run index.js.

src/db/mongoose.js

import mongoose from "mongoose";

mongoose.set('strictQuery', false);
mongoose.connect('mongodb://127.0.0.1:27017/task-manager-api');

src/index.js

import express from 'express';
import * from './db/mongoose.js';

I don't want to import anything from mongoose.js, just that it runs (which contains the connection statement) when I run index.js. I know I can achieve it using Common JS require('./db/mongoose.js') but I want to do it using ES6 imports. Thanks in advance.

CodePudding user response:

Just create a function connectDB. Inside the function create connection to mongodb.

src/db/mongoose.js

import mongoose from "mongoose";

export default function connectDB()
{
mongoose.set('strictQuery', false);
mongoose.connect('mongodb://127.0.0.1:27017/task-manager-api');
}

import and call the function inside index.js

src/index.js

import connectDB from "./db/mongoose.js";

connectDB();
  • Related