node.js - 如何在没有 Mongoose 的情况下使用 express 连接到 mongodb?

标签 node.js mongodb express mongoose

我正在使用 express 框架,并且想在不使用 mongoose 的情况下连接到 mongodb,但使用 native nodejs Mongodb 驱动程序。在不每次都创建新连接的情况下如何做到这一点?

为了处理 get 或 post 请求,我目前为每个请求打开一个到数据库的新连接,并在请求完成时关闭它。有一个更好的方法吗?提前致谢。

最佳答案

按照我评论中的示例,对其进行修改,以便应用处理错误而不是无法启动服务器。

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

var MongoClient = require('mongodb').MongoClient;
var dbURL = "mongodb://localhost:27017/integration_test";
var db;

// Initialize connection once
MongoClient.connect(dbURL, function(err, database) {
  if(err) return console.error(err);

  db = database;

  // the Mongo driver recommends starting the server here 
  // because most apps *should* fail to start if they have no DB.
  // If yours is the exception, move the server startup elsewhere. 
});

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

app.use(function(err, req, res){
  // handle error here.  For example, logging and 
  // returning a friendly error page
});

// Starting the app here will work, but some users 
// will get errors if the db connection process is slow.  
app.listen(3000);
console.log("Listening on port 3000");

关于node.js - 如何在没有 Mongoose 的情况下使用 express 连接到 mongodb?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36374842/

相关文章:

javascript - 为什么我们在使用方法之前添加 req.user 对象?

javascript - NodeJS 中使用 bluebird Promise 的链函数

mongodb - 如何将 Mongoose 聚合结果转换为特定的文档模式类型?

javascript - .ejs 模板中的 Bootstrap 分页

javascript - MongoDB JS,查找并返回

spring - 在 Spring 解决 mongodb 引用

javascript - 多环境Express Api

node.js - Ember.js、Express.js 和 Node.js 的 Assets 管道?

node.js - Mongoose $push 的问题

node.js - 使用 ejabberd 进行浏览器内聊天