如何在NodeJS中引用与MongoDB的连接

时间:2015-03-10 06:17:58

标签: node.js mongodb

我有以下代码:

var db;

MongoClient.connect("mongodb://localhost:27017/mobregserver", function(err, database) {
  if(!err) {
    console.log("We are connected");
  }

  db = database;

});

db.collection('bbr').insert({fields: "fields", files: "files"}, {upsert:true}, function(err, result) {
      if(!err){
        console.log("written");
      }
});

我得到以下输出:

我们已经联系

TypeError:无法调用未定义的方法'collection'

2 个答案:

答案 0 :(得分:0)

Connect方法是asyncrone,因此您的db变量将在稍后初始化,然后您开始使用它。试试这段代码:

MongoClient.connect("mongodb://localhost:27017/mobregserver", function(err, database) {
  if(err) {
    // Here, it may be better to interrupt further work in case of error
    console.log('fail', err);
    return;
  }

  var db = database;

  db.collection('bbr').insert({fields: "fields", files: "files"}, {upsert:true}, function(err, result) {
          if(!err){
            console.log("written");
          }
    });
});

修改

nodejs服务器的完整示例,取自here

var express = require('express');
var mongodb = require('mongodb');
var app = express();

var MongoClient = require('mongodb').MongoClient;
var db;

// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) {
  if(err) throw err;

  db = database;

  // Start the application after the database connection is ready
  app.listen(3000);
  console.log("Listening on port 3000");
});

// Reuse database object in request handlers
app.get("/", function(req, res) {
  db.collection("replicaset_mongo_client_collection").find({}, function(err, docs) {
    docs.each(function(err, doc) {
      if(doc) {
        console.log(doc);
      }
      else {
        res.end();
      }
    });
  });
});

答案 1 :(得分:0)

    var db;

    MongoClient.connect("mongodb://localhost:27017/mobregserver", function(err, database) {
      if(!err) {
        console.log("We are connected");


      db = database;
    db.collection('bbr').insert({fields: "fields", files: "files"}, {upsert:true}, function(err, result) {
          if(!err){
            console.log("written");
          }

    });
    }
    });