Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!