I am getting the error in connecting nodejs with mongodb

const { MongoClient } = require(“mongodb”);
//const assert = require(‘assert’);
// Replace the uri string with your connection string.
const url = " mongodb://localhost:27017";

const client = new MongoClient(url);

//const dbName= ‘myproject’;

async function run() {
try {
const database = client.db(‘fruitsDB’);
const fruits = database.collection(‘fruits’);

// Query for a movie that has the title 'Back to the Future'
// const query = { title: 'Back to the Future' };
// const fruit = await fruits.findOne(query);
await fruits.insertMany([
    {
        name: "Apple",
        score: 8,
        review: "Great fruit"
    },

    {
        name: "Orange",
        score: 6,
        review: "Kinda Sour"
    },
    
    {
        name: "Banana",
        score: 9,
        review: "Great stuff!"
    }
    
])
console.log(fruit);

} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);

Error :
C:\Users\USER\Desktop\fruitsDb\node_modules\mongodb-connection-string-url\lib\index.js:86
throw new MongoParseError(‘Invalid scheme, expected connection string to start with “mongodb://” or “mongodb+srv://”’);
^

MongoParseError: Invalid scheme, expected connection string to start with “mongodb://” or “mongodb+srv://”
at new ConnectionString (C:\Users\USER\Desktop\fruitsDb\node_modules\mongodb-connection-string-url\lib\index.js:86:19)
at parseOptions (C:\Users\USER\Desktop\fruitsDb\node_modules\mongodb\lib\connection_string.js:191:17)
at new MongoClient (C:\Users\USER\Desktop\fruitsDb\node_modules\mongodb\lib\mongo_client.js:48:63)
at Object. (C:\Users\USER\Desktop\fruitsDb\app.js:6:16)
at Module._compile (node:internal/modules/cjs/loader:1254:14)
at Module._extensions…js (node:internal/modules/cjs/loader:1308:10)
at Module.load (node:internal/modules/cjs/loader:1117:32)
at Module._load (node:internal/modules/cjs/loader:958:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47

Node.js v18.16.0
[nodemon] app crashed - waiting for file changes before starting…

Please remove the space before “mongodb://” in the line of code const url = " mongodb://localhost:27017"; . It should be const url = "mongodb://localhost:27017"; . This correction should resolve the issue. If you have any further questions or encounter any other queries related to this, please let me know.

1 Like

It is not showing error but the database which I have created in Nodejs is not showing in mongodb