shyamji
shyamji

Reputation: 37

Node.js application gets MongoError connection closed

When I try to connect with node.js application I get:

MongoError: connection 0 to 127.0.0.1:27017 closed

var MongoClient = require('mongodb').MongoClient
 ,format = require('util').format;    
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {     
  if(err) throw err;
  var collection = db.collection('student');     
  collection.insert({id:4,name:shyam}, function(err, docs) {              
    collection.count(function(err, count) {         
      console.log(format("count = %s", count));
    });
    // Locate all the entries using find       
    collection.find().toArray(function(err, results) {
      console.dir(results);
      // Let's close the db
      db.close();
    });
  });
})

Upvotes: 2

Views: 2783

Answers (2)

Yash Bele
Yash Bele

Reputation: 686

var mongo=require("mongodb").MongoClient;
var assert=require("assert");
var url="mongodb://localhost:27017/<database-name>";
mongo.connect(url,function(err,db){
assert.equal(null,err);
//insert query
db.close();
});

Upvotes: 1

Daniel Taub
Daniel Taub

Reputation: 5379

Next time you should write better question.

var mongo = require('mongoose');

mongo.connect('mongodb://localhost:27017/dbname');

// Connect to mongo
var db = mongo.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log('Connected');
});

learn more about how to connect to MongoDB with node application Mongoose

Upvotes: 1

Related Questions