Access mongodb+nodjs from javascript?












0















I'm running a server with nodejs+mongodb:



let MongoClient = require('mongodb').MongoClient.connect("mongodb://localhost:27017/mydb", { useNewUrlParser: true } ),

(async () =>{
let client;
try {
client = await MongoClient;
...


I'm creating some data-visualizations and I need a simple way to access my backend data from javascript, is this possible? Ideally I would like full access.










share|improve this question



























    0















    I'm running a server with nodejs+mongodb:



    let MongoClient = require('mongodb').MongoClient.connect("mongodb://localhost:27017/mydb", { useNewUrlParser: true } ),

    (async () =>{
    let client;
    try {
    client = await MongoClient;
    ...


    I'm creating some data-visualizations and I need a simple way to access my backend data from javascript, is this possible? Ideally I would like full access.










    share|improve this question

























      0












      0








      0








      I'm running a server with nodejs+mongodb:



      let MongoClient = require('mongodb').MongoClient.connect("mongodb://localhost:27017/mydb", { useNewUrlParser: true } ),

      (async () =>{
      let client;
      try {
      client = await MongoClient;
      ...


      I'm creating some data-visualizations and I need a simple way to access my backend data from javascript, is this possible? Ideally I would like full access.










      share|improve this question














      I'm running a server with nodejs+mongodb:



      let MongoClient = require('mongodb').MongoClient.connect("mongodb://localhost:27017/mydb", { useNewUrlParser: true } ),

      (async () =>{
      let client;
      try {
      client = await MongoClient;
      ...


      I'm creating some data-visualizations and I need a simple way to access my backend data from javascript, is this possible? Ideally I would like full access.







      javascript node.js mongodb






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 14 '18 at 18:17









      HimmatorsHimmators

      5,6822686175




      5,6822686175
























          2 Answers
          2






          active

          oldest

          votes


















          3














          You have to build a bridge, e.g. using a REST API:



           // server.js
          // npm install express, body-parser, mongodb
          const app = require("express")();
          const bodyParser = require("body-parser");
          const db = require("mongodb").MongoClient.connect(/*...*/);

          app.use(bodyParser.json());

          app.post("/findOne", async (req, res) => {
          try {
          const connection = await db;
          const result = await connection.findOne(req.body);
          if(!result) throw new Error("Not found!");
          res.status(200).json(result);
          } catch(error) {
          res.status(500).json(error);
          }
          });

          // ... all those other methods ...

          app.listen(80);


          That way you can easily connect to it on the client:



           // client.js
          function findOne(query) {
          const result = await fetch("/findOne/", {
          method: "POST",
          body: JSON.stringify(query),
          headers:{
          'Content-Type': 'application/json'
          }
          });

          if(!result.ok) throw await result.json();

          return await result.json();
          }




          Note: I hope you are aware that you also allow some strangers to play with your database if you do not validate the requests properly / add authentication.






          share|improve this answer


























          • you missed a "dot", bodyParser.json()

            – Himmators
            Nov 14 '18 at 18:30



















          1














          For security purposes you should never do this, but hypothetically you could make an AJAX endpoint or WebSockets server on the node application that passes the input straight to mongoDB and takes the output straight back to the client.



          It would be a much better practice to write a simple API using AJAX requests or WS to prevent the user from compromising your database.






          share|improve this answer
























          • I know, there is no sensitive data in this database and I will only run it on my local machine...

            – Himmators
            Nov 14 '18 at 18:26











          • In that case, just do a JSON.parse on an http request, dump it into a query, and send the results of the query as the http response.

            – Gordon
            Nov 14 '18 at 18:28











          Your Answer






          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: "1"
          };
          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%2fstackoverflow.com%2fquestions%2f53306480%2faccess-mongodbnodjs-from-javascript%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3














          You have to build a bridge, e.g. using a REST API:



           // server.js
          // npm install express, body-parser, mongodb
          const app = require("express")();
          const bodyParser = require("body-parser");
          const db = require("mongodb").MongoClient.connect(/*...*/);

          app.use(bodyParser.json());

          app.post("/findOne", async (req, res) => {
          try {
          const connection = await db;
          const result = await connection.findOne(req.body);
          if(!result) throw new Error("Not found!");
          res.status(200).json(result);
          } catch(error) {
          res.status(500).json(error);
          }
          });

          // ... all those other methods ...

          app.listen(80);


          That way you can easily connect to it on the client:



           // client.js
          function findOne(query) {
          const result = await fetch("/findOne/", {
          method: "POST",
          body: JSON.stringify(query),
          headers:{
          'Content-Type': 'application/json'
          }
          });

          if(!result.ok) throw await result.json();

          return await result.json();
          }




          Note: I hope you are aware that you also allow some strangers to play with your database if you do not validate the requests properly / add authentication.






          share|improve this answer


























          • you missed a "dot", bodyParser.json()

            – Himmators
            Nov 14 '18 at 18:30
















          3














          You have to build a bridge, e.g. using a REST API:



           // server.js
          // npm install express, body-parser, mongodb
          const app = require("express")();
          const bodyParser = require("body-parser");
          const db = require("mongodb").MongoClient.connect(/*...*/);

          app.use(bodyParser.json());

          app.post("/findOne", async (req, res) => {
          try {
          const connection = await db;
          const result = await connection.findOne(req.body);
          if(!result) throw new Error("Not found!");
          res.status(200).json(result);
          } catch(error) {
          res.status(500).json(error);
          }
          });

          // ... all those other methods ...

          app.listen(80);


          That way you can easily connect to it on the client:



           // client.js
          function findOne(query) {
          const result = await fetch("/findOne/", {
          method: "POST",
          body: JSON.stringify(query),
          headers:{
          'Content-Type': 'application/json'
          }
          });

          if(!result.ok) throw await result.json();

          return await result.json();
          }




          Note: I hope you are aware that you also allow some strangers to play with your database if you do not validate the requests properly / add authentication.






          share|improve this answer


























          • you missed a "dot", bodyParser.json()

            – Himmators
            Nov 14 '18 at 18:30














          3












          3








          3







          You have to build a bridge, e.g. using a REST API:



           // server.js
          // npm install express, body-parser, mongodb
          const app = require("express")();
          const bodyParser = require("body-parser");
          const db = require("mongodb").MongoClient.connect(/*...*/);

          app.use(bodyParser.json());

          app.post("/findOne", async (req, res) => {
          try {
          const connection = await db;
          const result = await connection.findOne(req.body);
          if(!result) throw new Error("Not found!");
          res.status(200).json(result);
          } catch(error) {
          res.status(500).json(error);
          }
          });

          // ... all those other methods ...

          app.listen(80);


          That way you can easily connect to it on the client:



           // client.js
          function findOne(query) {
          const result = await fetch("/findOne/", {
          method: "POST",
          body: JSON.stringify(query),
          headers:{
          'Content-Type': 'application/json'
          }
          });

          if(!result.ok) throw await result.json();

          return await result.json();
          }




          Note: I hope you are aware that you also allow some strangers to play with your database if you do not validate the requests properly / add authentication.






          share|improve this answer















          You have to build a bridge, e.g. using a REST API:



           // server.js
          // npm install express, body-parser, mongodb
          const app = require("express")();
          const bodyParser = require("body-parser");
          const db = require("mongodb").MongoClient.connect(/*...*/);

          app.use(bodyParser.json());

          app.post("/findOne", async (req, res) => {
          try {
          const connection = await db;
          const result = await connection.findOne(req.body);
          if(!result) throw new Error("Not found!");
          res.status(200).json(result);
          } catch(error) {
          res.status(500).json(error);
          }
          });

          // ... all those other methods ...

          app.listen(80);


          That way you can easily connect to it on the client:



           // client.js
          function findOne(query) {
          const result = await fetch("/findOne/", {
          method: "POST",
          body: JSON.stringify(query),
          headers:{
          'Content-Type': 'application/json'
          }
          });

          if(!result.ok) throw await result.json();

          return await result.json();
          }




          Note: I hope you are aware that you also allow some strangers to play with your database if you do not validate the requests properly / add authentication.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 14 '18 at 18:30

























          answered Nov 14 '18 at 18:25









          Jonas WilmsJonas Wilms

          58.4k43151




          58.4k43151













          • you missed a "dot", bodyParser.json()

            – Himmators
            Nov 14 '18 at 18:30



















          • you missed a "dot", bodyParser.json()

            – Himmators
            Nov 14 '18 at 18:30

















          you missed a "dot", bodyParser.json()

          – Himmators
          Nov 14 '18 at 18:30





          you missed a "dot", bodyParser.json()

          – Himmators
          Nov 14 '18 at 18:30













          1














          For security purposes you should never do this, but hypothetically you could make an AJAX endpoint or WebSockets server on the node application that passes the input straight to mongoDB and takes the output straight back to the client.



          It would be a much better practice to write a simple API using AJAX requests or WS to prevent the user from compromising your database.






          share|improve this answer
























          • I know, there is no sensitive data in this database and I will only run it on my local machine...

            – Himmators
            Nov 14 '18 at 18:26











          • In that case, just do a JSON.parse on an http request, dump it into a query, and send the results of the query as the http response.

            – Gordon
            Nov 14 '18 at 18:28
















          1














          For security purposes you should never do this, but hypothetically you could make an AJAX endpoint or WebSockets server on the node application that passes the input straight to mongoDB and takes the output straight back to the client.



          It would be a much better practice to write a simple API using AJAX requests or WS to prevent the user from compromising your database.






          share|improve this answer
























          • I know, there is no sensitive data in this database and I will only run it on my local machine...

            – Himmators
            Nov 14 '18 at 18:26











          • In that case, just do a JSON.parse on an http request, dump it into a query, and send the results of the query as the http response.

            – Gordon
            Nov 14 '18 at 18:28














          1












          1








          1







          For security purposes you should never do this, but hypothetically you could make an AJAX endpoint or WebSockets server on the node application that passes the input straight to mongoDB and takes the output straight back to the client.



          It would be a much better practice to write a simple API using AJAX requests or WS to prevent the user from compromising your database.






          share|improve this answer













          For security purposes you should never do this, but hypothetically you could make an AJAX endpoint or WebSockets server on the node application that passes the input straight to mongoDB and takes the output straight back to the client.



          It would be a much better practice to write a simple API using AJAX requests or WS to prevent the user from compromising your database.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 14 '18 at 18:23









          GordonGordon

          7217




          7217













          • I know, there is no sensitive data in this database and I will only run it on my local machine...

            – Himmators
            Nov 14 '18 at 18:26











          • In that case, just do a JSON.parse on an http request, dump it into a query, and send the results of the query as the http response.

            – Gordon
            Nov 14 '18 at 18:28



















          • I know, there is no sensitive data in this database and I will only run it on my local machine...

            – Himmators
            Nov 14 '18 at 18:26











          • In that case, just do a JSON.parse on an http request, dump it into a query, and send the results of the query as the http response.

            – Gordon
            Nov 14 '18 at 18:28

















          I know, there is no sensitive data in this database and I will only run it on my local machine...

          – Himmators
          Nov 14 '18 at 18:26





          I know, there is no sensitive data in this database and I will only run it on my local machine...

          – Himmators
          Nov 14 '18 at 18:26













          In that case, just do a JSON.parse on an http request, dump it into a query, and send the results of the query as the http response.

          – Gordon
          Nov 14 '18 at 18:28





          In that case, just do a JSON.parse on an http request, dump it into a query, and send the results of the query as the http response.

          – Gordon
          Nov 14 '18 at 18:28


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • 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%2fstackoverflow.com%2fquestions%2f53306480%2faccess-mongodbnodjs-from-javascript%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

          Bressuire

          Vorschmack

          Quarantine