如何在Express'中提供MongoDB。 HTTP方法?

时间:2016-02-13 14:10:08

标签: node.js mongodb express

我试图将MongoDB与Node / Express一起使用。我做了official example工作:

var express = require('express')
var MongoClient = require('mongodb').MongoClient
var assert = require('assert')
var app = express()

// Connection URL
var url = 'mongodb://localhost:27017/myproject'
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err)
  console.log("Connected correctly to server")

  insertDocuments(db, function() {
    db.close()
  })
})

var insertDocuments = function(db, callback) {
  // Get the documents collection
  var collection = db.collection('documents')
  // Insert some documents
  collection.insertMany([
    // Some code
  ], function(err, result) {
    // Some code
    callback(result)
  })
}

app.get('/insert-document', function(req, res) {
  // res.send()
})

我怎样才能让Mongo在Express' HTTP方法?例如,在insertDocuments()内使用app.get('/insert-document', function(req, res)

编辑(完整server.js文件):

var express = require('express')
// var PouchDB = require('pouchdb')
var MongoClient = require('mongodb').MongoClient
var assert = require('assert')
var webpack = require('webpack')
var config = require('./webpack.dev.conf')

var app = express()
var compiler = webpack(config)

// Connection URL
var url = 'mongodb://localhost:27017/myproject'
// Use connect method to connect to the Server
var db

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err)
  console.log("Connected correctly to server")
  db = db
})

var insertDocuments = function(db, callback) {
  // Get the documents collection
  var collection = db.collection('documents')
  // Insert some documents
  collection.insertMany([
    {a : 1}, {a : 2}, {a : 3}
  ], function(err, result) {
    assert.equal(err, null)
    assert.equal(3, result.result.n)
    assert.equal(3, result.ops.length)
    console.log("Inserted 3 documents into the document collection")
    callback(result)
  })
}

// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())

// serve webpack bundle output
app.use(require('webpack-dev-middleware')(compiler, {
  publicPath: config.output.publicPath,
  stats: {
    colors: true,
    chunks: false
  }
}))

// enable hot-reload and state-preserving
// compilation error display
app.use(require('webpack-hot-middleware')(compiler))

app.get('/docs', function(req, res) {
  // res.send()
  insertDocuments(db, function() {
    db.close()
  })
})

app.listen(8080, 'localhost', function (err) {
  if (err) {
    console.log(err)
    return
  }
  console.log('Listening at http://localhost:8080')
})

我得到了

  

TypeError:无法读取属性'集合'未定义的       在insertDocuments(/home/alex/node/project-mongo/build/dev-server.js:24:22)

1 个答案:

答案 0 :(得分:2)

引用代码here,将连接db保存为一个全局变量,示例代码如下所示。

var db;

MongoClient.connect(url, function(err, db) {
      assert.equal(null, err)
      console.log("Connected correctly to server")

      db = db;
      // 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('/insert-document', function(req, res) {
      // insertDocuments() could invoked here.
});