Mongo db with Monk: error catching and handling if db is down

前端 未结 1 1027
渐次进展
渐次进展 2021-01-14 18:40

I\'m new to Mongo. I needed a database for a simple project and ended up following a tutorial using Mongo with Monk but I have problems understanding how to handle errors.<

相关标签:
1条回答
  • 2021-01-14 19:21

    Well you can actually set the bufferMaxEntries option ( documented under Db but deprecated for that object usage, use at "top level as demonstrated instead" ) on the connection, which essentially stops "queuing" requests on the driver when no connection is actually present.

    As a minimal example:

    index.js

    const express = require('express'),
          morgan = require('morgan'),
          db = require('monk')('localhost/test',{ bufferMaxEntries: 0 }),
          app = express();
    
    const routes = require('./routes');
    
    app.use(morgan('combined'));
    
    app.use((req,res,next) => {
      req.db = db;
      next();
    });
    
    app.use('/', routes);
    
    (async function() {
    
      try {
    
        await db.then(() => 1);
    
        let collection = db.get('test');
        await collection.remove({});
    
        await collection.insert(Array(5).fill(1).map((e,i) => ({ a: i+1 })));
        console.log('inserted test data');
    
        await app.listen(3000,'0.0.0.0');
        console.log('App waiting');
    
      } catch(e) {
        console.error(e);
      }
    
    })();
    

    routes.js

    var router = require('express').Router();
    
    router.get('/', async (req,res) => {
      try {
        let db = req.db,
            collection = db.get('test');
    
        let response = await collection.find();
        res.json(response);
      } catch(e) {
        res.status(500).json(e);
      }
    });
    
    module.exports = router;
    

    So I am actually awaiting the database connection to at least be present on "start up" here, but really only for example since I want to insert some data to actually retrieve. It's not required, but the basic concept is to wait for the Promise to resolve:

    await db.then(() => 1);
    

    Kind of trivial, and not really required for your actual code. But I still think it's good practice.

    The real test is done by stopping mongod or otherwise making the server unreachable and then issuing a request.

    Since we set the connection options to { bufferMaxEntries: 0 } this means that immediately as you attempt to issue a command to the database, the failure will be returned if there is no actual connection present.

    Of course when the database becomes available again, you won't get the error and the instructions will happen normally.

    Without the option the default is to "en-queue" the operations until a connection is resolved and then the "buffer" is essentially "played".

    You can simulate this ( as I did ) by "stopping" the mongod daemon and issuing requests. Then "starting" the daemon and issuing requests. It should simply return the caught error response.

    NOTE: Not required, but in fact the whole purpose of async/await syntax is to make things like try..catch valid again, since you can actually scope as blocks rather than using Promise.catch() or err callback arguments to trap the errors. Same principles apply when either of those structures are actually in use though.

    0 讨论(0)
提交回复
热议问题