Setting up Mongo Connection from Express App on Google App-Engine











up vote
0
down vote

favorite












I am trying to setup a Mongo Connection to an Express App which would be deployed on Google App-Engine. I noticed some approaches like this:




// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) {
if(err) return console.error(err);
db = database;
// 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();
}
});
});
});



I had some concerns about DB server outages and how it would be able to handle those. Thankfully, Node MongoDB client reconnects when DB Server is up. The only issue is that when DB server is down, the requests take a lot of time to process.



I came up with a solution, which probably works. Just wanted to know If I am doing anything wrong(Ignore the messages) or is there any better way?



let mongoConn = null;
const getMongoConn = async() => {
if(!mongoConn) {
try {
mongoConn = await MongoClient.connect("mongodb://localhost:27017", { useNewUrlParser: true });
mongoConn.on("close", () => {
console.log("Mongo Connection closed.");
mongoConn = null;
})
} catch(err) {
console.error("Mongo Connection failed.");
return null;
}
}
return mongoConn;
}

const app = express();
app.get("/", async(req, res) => {
console.log("recieved");
const conn = await getMongoConn();
try {
const db = conn.db("testDb");
const result = await db.collection("test").find().toArray();
res.status(200).send(JSON.stringify(result)).end();
} catch (e) {
res.status(404).send("DB server is down").end();
}
});

app.listen(7000, () => console.log("Server started."));









share|improve this question




























    up vote
    0
    down vote

    favorite












    I am trying to setup a Mongo Connection to an Express App which would be deployed on Google App-Engine. I noticed some approaches like this:




    // Initialize connection once
    MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) {
    if(err) return console.error(err);
    db = database;
    // 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();
    }
    });
    });
    });



    I had some concerns about DB server outages and how it would be able to handle those. Thankfully, Node MongoDB client reconnects when DB Server is up. The only issue is that when DB server is down, the requests take a lot of time to process.



    I came up with a solution, which probably works. Just wanted to know If I am doing anything wrong(Ignore the messages) or is there any better way?



    let mongoConn = null;
    const getMongoConn = async() => {
    if(!mongoConn) {
    try {
    mongoConn = await MongoClient.connect("mongodb://localhost:27017", { useNewUrlParser: true });
    mongoConn.on("close", () => {
    console.log("Mongo Connection closed.");
    mongoConn = null;
    })
    } catch(err) {
    console.error("Mongo Connection failed.");
    return null;
    }
    }
    return mongoConn;
    }

    const app = express();
    app.get("/", async(req, res) => {
    console.log("recieved");
    const conn = await getMongoConn();
    try {
    const db = conn.db("testDb");
    const result = await db.collection("test").find().toArray();
    res.status(200).send(JSON.stringify(result)).end();
    } catch (e) {
    res.status(404).send("DB server is down").end();
    }
    });

    app.listen(7000, () => console.log("Server started."));









    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I am trying to setup a Mongo Connection to an Express App which would be deployed on Google App-Engine. I noticed some approaches like this:




      // Initialize connection once
      MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) {
      if(err) return console.error(err);
      db = database;
      // 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();
      }
      });
      });
      });



      I had some concerns about DB server outages and how it would be able to handle those. Thankfully, Node MongoDB client reconnects when DB Server is up. The only issue is that when DB server is down, the requests take a lot of time to process.



      I came up with a solution, which probably works. Just wanted to know If I am doing anything wrong(Ignore the messages) or is there any better way?



      let mongoConn = null;
      const getMongoConn = async() => {
      if(!mongoConn) {
      try {
      mongoConn = await MongoClient.connect("mongodb://localhost:27017", { useNewUrlParser: true });
      mongoConn.on("close", () => {
      console.log("Mongo Connection closed.");
      mongoConn = null;
      })
      } catch(err) {
      console.error("Mongo Connection failed.");
      return null;
      }
      }
      return mongoConn;
      }

      const app = express();
      app.get("/", async(req, res) => {
      console.log("recieved");
      const conn = await getMongoConn();
      try {
      const db = conn.db("testDb");
      const result = await db.collection("test").find().toArray();
      res.status(200).send(JSON.stringify(result)).end();
      } catch (e) {
      res.status(404).send("DB server is down").end();
      }
      });

      app.listen(7000, () => console.log("Server started."));









      share|improve this question















      I am trying to setup a Mongo Connection to an Express App which would be deployed on Google App-Engine. I noticed some approaches like this:




      // Initialize connection once
      MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) {
      if(err) return console.error(err);
      db = database;
      // 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();
      }
      });
      });
      });



      I had some concerns about DB server outages and how it would be able to handle those. Thankfully, Node MongoDB client reconnects when DB Server is up. The only issue is that when DB server is down, the requests take a lot of time to process.



      I came up with a solution, which probably works. Just wanted to know If I am doing anything wrong(Ignore the messages) or is there any better way?



      let mongoConn = null;
      const getMongoConn = async() => {
      if(!mongoConn) {
      try {
      mongoConn = await MongoClient.connect("mongodb://localhost:27017", { useNewUrlParser: true });
      mongoConn.on("close", () => {
      console.log("Mongo Connection closed.");
      mongoConn = null;
      })
      } catch(err) {
      console.error("Mongo Connection failed.");
      return null;
      }
      }
      return mongoConn;
      }

      const app = express();
      app.get("/", async(req, res) => {
      console.log("recieved");
      const conn = await getMongoConn();
      try {
      const db = conn.db("testDb");
      const result = await db.collection("test").find().toArray();
      res.status(200).send(JSON.stringify(result)).end();
      } catch (e) {
      res.status(404).send("DB server is down").end();
      }
      });

      app.listen(7000, () => console.log("Server started."));






      node.js mongodb google-apps-script google-app-engine






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 16 at 1:56









      Jamal

      30.2k11115226




      30.2k11115226










      asked Nov 15 at 17:08









      Sandeep Mishra

      11




      11



























          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          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',
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          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%2fcodereview.stackexchange.com%2fquestions%2f207738%2fsetting-up-mongo-connection-from-express-app-on-google-app-engine%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f207738%2fsetting-up-mongo-connection-from-express-app-on-google-app-engine%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

          Сан-Квентин

          8-я гвардейская общевойсковая армия

          Алькесар