MongoDB
 sql >> Teknologi Basis Data >  >> NoSQL >> MongoDB

Bagaimana saya bisa terhubung ke mongodb menggunakan express tanpa luwak?

Mengikuti contoh dari komentar saya, memodifikasinya sehingga aplikasi menangani kesalahan daripada gagal memulai server.

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");


  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. warisan dalam database dokumen?

  2. MongoDB v2.4.9 urutkan berdasarkan bidang boolean

  3. MongoDB + Node.js:tidak dapat memasukkan tanggal dengan benar

  4. PouchDB/CouchDB seperti alternatif untuk MongoDB

  5. MongoDB $keDesimal