-1

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?

0xd6438c
  • 1
  • 3
  • @Bravo could you please actually read my post? Title edited for clarity. – 0xd6438c May 12 '22 at 09:11
  • Why would I read a question when the title makes no sense? Hopefully my comment has made your question likely to be read – Bravo May 12 '22 at 09:12

1 Answers1

0

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.

Johannes Stadler
  • 737
  • 12
  • 24