Search code examples
javascriptnode.jsmongodbdeploymentnode-modules

monodb.js:2 Uncaught ReferenceError: require is not defined at monodb.js:2:25



    const { MongoClient } = require("mongodb")
    const url='mongodb://localhost:27017'
    const client=new MongoClient(url);
    async function getdata(){
        let result=await client.connect();
        let db=result.db("first")
        let collection=db.collection("c1");
        let res=await collection.find({}).toArray()
        console.log(collection.find({}).toArray())
    }
    getdata()

I'm getting this error:

monodb.js:1 Uncaught SyntaxError: Cannot use import statement outside a module (at monodb.js:1:1)

on this line

const { MongoClient } = require("mongodb")

I've installed mongodb nodejs driver what can i do to solve this problem?


Solution

  • You have given 2 different error messages. In your title the error says:

    monodb.js:2 Uncaught ReferenceError: require is not defined at monodb.js:2:25
    

    But in your question you say the error is:

    monodb.js:1 Uncaught SyntaxError: Cannot use import statement outside a module (at monodb.js:1:1)
    

    Either way the most likely cause is you are trying to use CommonJS require statements but you have defined the "type": "module" properties in your package.json. Or you are trying to use the ESM approach to importing modules by using import statements without defining "type": "module".

    If you have defined the "type": "module" properties in your package.json then you will have to adopt the ESM approach to importing modules by using import statements. You can't mix require statements in a project defined as "type": "module". If you want to keep using the require keyword you will have to remove the "type": "module" from your package.json.

    Try this instead:

    import { MongoClient } from 'mongodb';
    

    Here are the docs which are a great resource for starting off with MongoDB on Node.js. I suggest you follow.

    If you want to use ESM modules in your clinet-side JavaScript (i.e. in the browser) then make sure you add the type="module" attribute in the <script> tag like so:

    <script type="module" src="myfilename.js"></script>  
    

    Please note: bear in mind you won't be able to import packages in Node and then use them on the client-side.