Home > Net >  How does one get a value from <input> in an HTML file being run in NodeJS to a MongoDB db
How does one get a value from <input> in an HTML file being run in NodeJS to a MongoDB db

Time:05-13

Say, I wanted to get a certain value entered by a user in an HTML being run on NodeJS to be saved in my db, how would I do that?

I could get the value from HTML via the DOM, sure. Say example.html were being run via NodeJS like so:

var fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('example.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

I could get my value via the the DOM from example.html, like so:

var valuetobegotten = document.getElementById('valuetobegotten').value; 

But that only happens in the front-end HTML. I do understand that you need a MongoDB driver to be able to interact with MongoDB via NodeJS. And need to set something like this up:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:8080";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");
  db.close();
});

But, when I try to pull in valuetobegotten pulled in via the DOM earlier — by inserting it into a MongoDB collection, how does MongoDB know where to look to? Does it look to the url at JS files running on the same server? Like so:

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  var valuetogotten = valuetobegotten;
  dbo.collection("values").insertOne(valuetobegotten, function(err, res) {
    if (err) throw err;
    console.log("1 document inserted");
    db.close();
  });
}); 

Is that how it's done?

CodePudding user response:

You need to send the value from the browser back to your node server:

 ---------    <-1-   ---------    -3->   ----------  
| BROWSER |   -2->  | SERVER  |         | DATABASE |
 ---------           ---------           ----------  

What you currently implemented is 1 (serving the HTML) and 3 (storing something in the DB), but not 2 (sending the value from the HTML in the browser to the node server). So the value you fetched in your HTML needs to be sent to an (not yet existing) endpoint in your node server that then calls the MongoClient.

  • Related