skip to Main Content

I am new to JavaScript and currently learning mongoDB with node and mongoose. when I try to connect
with db, i got this error:

Did you mean to import ../config/dbConfig.js?
at finalizeResolution (node:internal/modules/esm/resolve:255:11)
at moduleResolve (node:internal/modules/esm/resolve:908:10)
at defaultResolve (node:internal/modules/esm/resolve:1121:11) at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:396:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:365:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:240:38)
at ModuleWrap. (node:internal/modules/esm/module_job:85:39)
at link (node:internal/modules/esm/module_job:84:36) {
code: ‘ERR_MODULE_NOT_FOUND’,

Please let me know where i did wrong and how to correct it in async & await?

dbconfig.js

import mongoose from 'mongoose';

mongoose.connect(process.env.MONGO_URI, {
    useNewUrlParser: true, useUnifiedTopology: true
});

const connection = mongoose.connection;

connection.on('error', () => {
    console.log('Error in connection to Database');
});

connection.on('connected', () => {
    console.log('Connected to Database')
});

module.exports = mongoose;

index.js

import express from 'express';
const app = express();
require('dotenv').config();
import mongoose from './config/dbConfig';
const port = process.env.PORT || 3001;


app.listen(port, () => {
    console.log(`Server running on localhost:${port}`)
});

2

Answers


  1. You should create a object mongoose connect and return it in dbconfig.js. In index.js, you use this object to startup app and connect db. Example:

    dbconfig.js

    const mongoose = require('mongoose');
    const logger = require('./logger');
    
    function makeNewConnection(uri) {
        const db = mongoose.createConnection(uri, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });
    
        emitDbEvent(db);
        return db;
    }
    
    function emitDbEvent(connection) {
        connection.on('error', function (error) {
            logger.info(`database:: connection ${this.name} ${JSON.stringify(error)}`);
            connection.close().catch(() => console.log(`MongoDB :: failed to close connection ${this.name}`));
        });
    
        connection.on('connected', function () {
            logger.info(`database:: connected ${this.name}`);
        });
    
        connection.on('disconnected', function () {
            logger.info(`database:: disconnected ${this.name}`);
        });
    }
    
    const connectMongo = makeNewConnection(process.env.MONGO_URI);
    
    module.exports = {
        connectMongo,
    };
    

    index.js

    import express from 'express';
    const app = express();
    require('dotenv').config();
    const { connectMongo } = require('./dbconfig');
    const port = process.env.PORT || 3001;
    
    await connectMongo();
    
    app.listen(port, () => {
        console.log(`Server running on localhost:${port}`)
    });
    
    Login or Signup to reply.
  2. Your code is over engineered, connecting with mongoose is a fairly straightforward process. You seem to be using ES Module syntax so you can’t really mix require() and import together so I will provide an example using ES Module syntax. Please note that in future you need to provide a file extension to your modules that you import, i.e. you need to include the .js file extension.

    import express from 'express';
    import mongoose from 'mongoose';
    import 'dotenv/config';
    const app = express();
    const port = process.env.PORT || 3001;
    mongoose.connect(process.env.MONGO_URI).then(() => {
       console.log('Connected to MongoDB');
    })
    
    app.listen(port, () => {
        console.log(`Server running on localhost:${port}`)
    });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search