skip to Main Content

I am following W3Schools.com’s ‘Node.js MongoDB’ tutorial. My action.js file contains the following code:

var mongo = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";

mongo.connect(url, function (err, db) {
  if (err) throw err;
  console.log("Database created!");
  db.close();
});

When I try to run the file using node action.js, nothing happens. Even after going through several forums I can’t figure out what is going on.
This is the same question but at least that person is getting some error, which I’m not.

Terminal screenshot after executing Node.js command

mongod --version
db version v8.0.1
Build Info: {
    "version": "8.0.1",
    "gitVersion": "fcbe67d668fff5a370e2d87b9b1f74bc11bb7b94",
    "modules": [],
    "allocator": "tcmalloc-gperf",
    "environment": {
        "distmod": "windows",
        "distarch": "x86_64",
        "target_arch": "x86_64"
    }
}
mongosh --version
2.3.2

I tried changing the //localhost:27017 to 127.0.0.1:27017 as lots of other solutions have mentioned but it didn’t make any difference.

2

Answers


  1. Try instead this script which works:

    
    const { MongoClient } = require('mongodb');
    
    // Connection URL
    const url = 'mongodb://localhost:27017';
    const client = new MongoClient(url);
    
    // Database Name
    const dbName = 'mydb';
    
    async function main() {
        // Use connect method to connect to the server
        await client.connect();
        console.log('Connected successfully to server');
        const db = client.db(dbName);
        const collection = db.collection('documents');
    
        // the following code examples can be pasted here...
    
        return 'done.';
    }
    
    main()
        .then(console.log)
        .catch(console.error)
        .finally(() => client.close());
    
    
    Login or Signup to reply.
  2. Did you start the server mongodb before all?
    Below is the string to start the server on my linux machine

    sudo mongod –noauth –port 27017 –dbpath /var/lib/mongodb

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search