Node.js应用程序关闭MongoError连接

时间:2017-05-06 18:40:10

标签: node.js mongodb

当我尝试连接node.js应用程序时,我得到:

  

MongoError:连接0到127.0.0.1:27017已关闭

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();
    });
  });
})

2 个答案:

答案 0 :(得分:1)

下次你应该写更好的问题。

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');
});
  

详细了解如何使用节点连接MongoDB   申请Mongoose

答案 1 :(得分:1)

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();
});