Best way to handle 'MongoError: failed to connect to server on first connect' in Mongoose Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Come Celebrate our 10 Year Anniversary!Problems with MongoDB server, (anon):1137 exception connect failedSystemd - run script/unit after system crashSet RemainAfterExit=no for a classic init script in systemdHow to boot after Systemd startup into program/scriptIntrospection of initramfs systemd services - How?systemd restart jobs on conditionsystemd: when during boot are network interface devices createdNode.JS systemd service won't restartHow to restrict access to GPU?

An adverb for when you're not exaggerating

Should I use a zero-interest credit card for a large one-time purchase?

Performance gap between bool std:vector and array

Why aren't air breathing engines used as small first stages?

Why do we bend a book to keep it straight?

How can I reduce the gap between left and right of cdot with a macro?

Is there any word for a place full of confusion?

Why doesn't SQL Optimizer use my constraint?

How could we fake a moon landing now?

How does the math work when buying airline miles?

Significance of Cersei's obsession with elephants?

Is it possible for SQL statements to execute concurrently within a single session in SQL Server?

Can an alien society believe that their star system is the universe?

Maximum summed subsequences with non-adjacent items

Question about debouncing - delay of state change

Denied boarding although I have proper visa and documentation. To whom should I make a complaint?

Why is Nikon 1.4g better when Nikon 1.8g is sharper?

AppleTVs create a chatty alternate WiFi network

What is a fractional matching?

Dating a Former Employee

How to compare two different files line by line in unix?

Amount of permutations on an NxNxN Rubik's Cube

When a candle burns, why does the top of wick glow if bottom of flame is hottest?

Is grep documentation about ignoring case wrong, since it doesn't ignore case in filenames?



Best way to handle 'MongoError: failed to connect to server on first connect' in Mongoose



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)
Come Celebrate our 10 Year Anniversary!Problems with MongoDB server, (anon):1137 exception connect failedSystemd - run script/unit after system crashSet RemainAfterExit=no for a classic init script in systemdHow to boot after Systemd startup into program/scriptIntrospection of initramfs systemd services - How?systemd restart jobs on conditionsystemd: when during boot are network interface devices createdNode.JS systemd service won't restartHow to restrict access to GPU?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















In this GitHub issue for mongoose the developer stated that it is intended behaviour to crash the Node.js process if the initial database connection to MongoDB fails. It does this instead of trying to reconnect.



In my code I catch this error because I want to log it.



var mongooseOptions = 
useMongoClient: true,
reconnectInterval: 10000,
reconnectTries: Number.MAX_VALUE
;

mongoose.connect(connectionString, mongooseOptions)
.catch(err =>
logger.error('Mongodb first connection failed: ' + err.stack);
// what to do here? - process.exit(0); maybe?
);


But after that, what is the best practice to do?
crash the process? or write my own reconnecting logic? I maybe should mention that the mongodb.service is listed as a requirement for the node.service to start (using systemd in linux).



[Unit]
After=mongodb.service
...


I am also unsure how often I can expect to see this happen.



I have also used this guide but I cannot find a clear answer.










share|improve this question






























    2















    In this GitHub issue for mongoose the developer stated that it is intended behaviour to crash the Node.js process if the initial database connection to MongoDB fails. It does this instead of trying to reconnect.



    In my code I catch this error because I want to log it.



    var mongooseOptions = 
    useMongoClient: true,
    reconnectInterval: 10000,
    reconnectTries: Number.MAX_VALUE
    ;

    mongoose.connect(connectionString, mongooseOptions)
    .catch(err =>
    logger.error('Mongodb first connection failed: ' + err.stack);
    // what to do here? - process.exit(0); maybe?
    );


    But after that, what is the best practice to do?
    crash the process? or write my own reconnecting logic? I maybe should mention that the mongodb.service is listed as a requirement for the node.service to start (using systemd in linux).



    [Unit]
    After=mongodb.service
    ...


    I am also unsure how often I can expect to see this happen.



    I have also used this guide but I cannot find a clear answer.










    share|improve this question


























      2












      2








      2








      In this GitHub issue for mongoose the developer stated that it is intended behaviour to crash the Node.js process if the initial database connection to MongoDB fails. It does this instead of trying to reconnect.



      In my code I catch this error because I want to log it.



      var mongooseOptions = 
      useMongoClient: true,
      reconnectInterval: 10000,
      reconnectTries: Number.MAX_VALUE
      ;

      mongoose.connect(connectionString, mongooseOptions)
      .catch(err =>
      logger.error('Mongodb first connection failed: ' + err.stack);
      // what to do here? - process.exit(0); maybe?
      );


      But after that, what is the best practice to do?
      crash the process? or write my own reconnecting logic? I maybe should mention that the mongodb.service is listed as a requirement for the node.service to start (using systemd in linux).



      [Unit]
      After=mongodb.service
      ...


      I am also unsure how often I can expect to see this happen.



      I have also used this guide but I cannot find a clear answer.










      share|improve this question
















      In this GitHub issue for mongoose the developer stated that it is intended behaviour to crash the Node.js process if the initial database connection to MongoDB fails. It does this instead of trying to reconnect.



      In my code I catch this error because I want to log it.



      var mongooseOptions = 
      useMongoClient: true,
      reconnectInterval: 10000,
      reconnectTries: Number.MAX_VALUE
      ;

      mongoose.connect(connectionString, mongooseOptions)
      .catch(err =>
      logger.error('Mongodb first connection failed: ' + err.stack);
      // what to do here? - process.exit(0); maybe?
      );


      But after that, what is the best practice to do?
      crash the process? or write my own reconnecting logic? I maybe should mention that the mongodb.service is listed as a requirement for the node.service to start (using systemd in linux).



      [Unit]
      After=mongodb.service
      ...


      I am also unsure how often I can expect to see this happen.



      I have also used this guide but I cannot find a clear answer.







      mongodb node.js systemd ubuntu-16.04 error-handling






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 5 '17 at 14:14







      NG.

















      asked Dec 5 '17 at 14:08









      NG.NG.

      1317




      1317




















          1 Answer
          1






          active

          oldest

          votes


















          1














          I am also looking for an answer to your question. So far in my search I believe that calling process.exit is perahps the best method. Because Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB. That's because mongoose buffers model function calls internally.



          As of Mongoose 5.0.10 - Mongoose will not throw any errors by default if you use a model without connecting.



          If your connection fails to reconnect, then your app is thinking that it is performing the model operations via the buffer when in fact it will fail.



          I've seen developers add an additional Mongodb URI like this:



          mongoose.connect(URI1||URI2);


          Ultimately, you'll want to ensure your app will always be able to connect to the database rather than perform model functions into the buffer in futility.



          There is an option to disable buffering but I'm not sure how that will impact performance.






          share|improve this answer























            Your Answer








            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "2"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fserverfault.com%2fquestions%2f886661%2fbest-way-to-handle-mongoerror-failed-to-connect-to-server-on-first-connect-in%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            I am also looking for an answer to your question. So far in my search I believe that calling process.exit is perahps the best method. Because Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB. That's because mongoose buffers model function calls internally.



            As of Mongoose 5.0.10 - Mongoose will not throw any errors by default if you use a model without connecting.



            If your connection fails to reconnect, then your app is thinking that it is performing the model operations via the buffer when in fact it will fail.



            I've seen developers add an additional Mongodb URI like this:



            mongoose.connect(URI1||URI2);


            Ultimately, you'll want to ensure your app will always be able to connect to the database rather than perform model functions into the buffer in futility.



            There is an option to disable buffering but I'm not sure how that will impact performance.






            share|improve this answer



























              1














              I am also looking for an answer to your question. So far in my search I believe that calling process.exit is perahps the best method. Because Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB. That's because mongoose buffers model function calls internally.



              As of Mongoose 5.0.10 - Mongoose will not throw any errors by default if you use a model without connecting.



              If your connection fails to reconnect, then your app is thinking that it is performing the model operations via the buffer when in fact it will fail.



              I've seen developers add an additional Mongodb URI like this:



              mongoose.connect(URI1||URI2);


              Ultimately, you'll want to ensure your app will always be able to connect to the database rather than perform model functions into the buffer in futility.



              There is an option to disable buffering but I'm not sure how that will impact performance.






              share|improve this answer

























                1












                1








                1







                I am also looking for an answer to your question. So far in my search I believe that calling process.exit is perahps the best method. Because Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB. That's because mongoose buffers model function calls internally.



                As of Mongoose 5.0.10 - Mongoose will not throw any errors by default if you use a model without connecting.



                If your connection fails to reconnect, then your app is thinking that it is performing the model operations via the buffer when in fact it will fail.



                I've seen developers add an additional Mongodb URI like this:



                mongoose.connect(URI1||URI2);


                Ultimately, you'll want to ensure your app will always be able to connect to the database rather than perform model functions into the buffer in futility.



                There is an option to disable buffering but I'm not sure how that will impact performance.






                share|improve this answer













                I am also looking for an answer to your question. So far in my search I believe that calling process.exit is perahps the best method. Because Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB. That's because mongoose buffers model function calls internally.



                As of Mongoose 5.0.10 - Mongoose will not throw any errors by default if you use a model without connecting.



                If your connection fails to reconnect, then your app is thinking that it is performing the model operations via the buffer when in fact it will fail.



                I've seen developers add an additional Mongodb URI like this:



                mongoose.connect(URI1||URI2);


                Ultimately, you'll want to ensure your app will always be able to connect to the database rather than perform model functions into the buffer in futility.



                There is an option to disable buffering but I'm not sure how that will impact performance.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 16 '18 at 16:14









                metal_jacke1metal_jacke1

                261




                261



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Server Fault!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fserverfault.com%2fquestions%2f886661%2fbest-way-to-handle-mongoerror-failed-to-connect-to-server-on-first-connect-in%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to write a 12-bar blues melodyI-IV-V blues progressionHow to play the bridges in a standard blues progressionHow does Gdim7 fit in C# minor?question on a certain chord progressionMusicology of Melody12 bar blues, spread rhythm: alternative to 6th chord to avoid finger stretchChord progressions/ Root key/ MelodiesHow to put chords (POP-EDM) under a given lead vocal melody (starting from a good knowledge in music theory)Are there “rules” for improvising with the minor pentatonic scale over 12-bar shuffle?Confusion about blues scale and chords

                    What if the end-user didn't have the required library?What is setup.py?What is a clean, pythonic way to have multiple constructors in Python?What does Ruby have that Python doesn't, and vice versa?What is the reason for having '//' in Python?How do I create a namespace package in Python?How to package shared objects that python modules depend on?setuptools vs. distutils: why is distutils still a thing?Navigation in Windows 10 vs code not going to virtualenv library when the same library is installed at user levelPython create package for local usePackaging a project that uses multiple python versionsWhy is permission denied on pip install except for when “--user” is included at end of command?

                    Esgonzo ibérico Índice Descrición Distribución Hábitat Ameazas Notas Véxase tamén "Acerca dos nomes dos anfibios e réptiles galegos""Chalcides bedriagai"Chalcides bedriagai en Carrascal, L. M. Salvador, A. (Eds). Enciclopedia virtual de los vertebrados españoles. Museo Nacional de Ciencias Naturales, Madrid. España.Fotos