Skip to content
Advertisement

ReferenceError: require is not defined MongoDB

I’m trying to connect to my MongoDB database and I’m getting this error

ReferenceError: require is not defined
    at file:///Users/admin/mjml/mjml/playground.js:1:21
    at ModuleJob.run (node:internal/modules/esm/module_job:146:23)
    at async Loader.import (node:internal/modules/esm/loader:165:24)
    at async Object.loadESM (node:internal/process/esm_loader:68:5)
const MongoClient = require('mongodb').MongoClient
const uri =
  '------------------------------'
const client = new MongoClient(uri, { useNewUrlParser: true })
client.connect((err) => {
  const collection = client.db('test').collection('devices')
  // perform actions on the collection object
  client.close()
})

Advertisement

Answer

You are attempting to use require() inside an ESM module (you can see the Object.loadESM in the call stack of the error) which tells us it’s an ESM module. You can’t use require() in that type of module. Instead, you must use import.

So, you probably want:

import {MongoClient} from "mongodb";
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement