微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

node.js – 如何使用express而不使用mongoose连接到mongodb?

我正在使用快速框架,并希望连接到 mongodb而不使用mongoose,但使用本机nodejs Mongodb驱动程序.如何在不创建新连接的情况下执行此操作?

为了处理get或post请求,我当前为每个请求打开一个与db的新连接,并在请求完成时关闭它.有一个更好的方法吗?提前致谢.

解决方法

按照我的评论示例,修改它以便应用程序处理错误而不是无法启动服务器.
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) 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) {
  db.collection("replicaset_mongo_client_collection").find({},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");

原文地址:https://www.jb51.cc/nodejs/241273.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐