0

I need how to set username and password in mongodb program. I tried it shows unable to connect database. What is the error in that url link?

var mongodb=require("mongodb");
var mongoclient=mongodb.MongoClient;
var url="mongodb://viki:vino@localhost:27017/details";
mongoclient.connect(url,function(err,db)
{
    if(err)
    {
        console.log("unable to connect the database");
    }
    else
    {
        console.log("connect the details database successfully");
        var collection=db.collection("users");
        var user4= {
            "name":"princy",
            "age":21,
            "subject":["English","Grammar"],
            "address": {
                "city": "Rahim nagar",
                "state": "Tamilnadu",
                "pincode": "582028237"
            }
        };
        collection.insert(user4,function(err,result)
        {
            if(err)
            {
                console.log("not inserted");
            }
            else {
                console.log("%d documents inserted",result.length);
                console.log("Result:"+result);
            }
        });
        db.close();
    }
});
halfer
  • 19,824
  • 17
  • 99
  • 186
  • Can you print `console.log(err)` inside `if(err)` and paste the output? – harshavmb Jun 04 '17 at 09:44
  • You can also try `MongoClient.connect('mongodb://viki:vino@localhost:27017/details', function (err, db) {}` without creating `mongoClient` and `url` variables – harshavmb Jun 04 '17 at 09:47
  • You are calling `db.close()` outside of the async callback to `insert()`. It needs to be inside otherwise your program will terminate before it does anything. This is almost certainly your actual problem. – Neil Lunn Jun 04 '17 at 09:48
  • I followed based on harshavmb comment but it is not working.It shows an error – Vignesh Ravi Jun 04 '17 at 09:51

0 Answers0