How can I connect to mongodb using express without mongoose?

后端 未结 2 1807
情话喂你
情话喂你 2021-02-04 16:26

I am using the express framework and would like to connect to a mongodb without using mongoose, but with the native nodejs Mongodb driver. How can I do this without creating a n

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-04 16:46

    Following the example from my comment, modifying it so that the app handles errors rather than failing to start the server.

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

提交回复
热议问题