Node.js: extracting data from form and submitting to Mongo db

Using Node and Express. How would I go about saving all the request data to an array, and then insert each item from the array to a mongo collection?

My route is currently setup like this: app.post("/addbulletin", routes.addbulletin(db));

And I'm handling the view and processing the data like so:

exports.addbulletin = function(db) {
  return function(req, res) {

    // Get our form values. These rely on the "name" attributes
    var date = req.body.date,
        name = req.body.name;
        // and many more...

    // Submit to the DB
    collection.insert({
      "date" : date,
      "name" : name
      // and many more...
    }, function (err, data) {
      if (err) {
        res.send("There was a problem adding the information to the database.");
      }
      else {
        res.location("index");
        res.redirect("/");
      }
    });

  }
}

The problem with this way is that I have to know all of the items that need sent to the database. What if I don't know what fields will be on a page to grab the data from? That's exactly the situation I'm in currently, because I have a form that's populating inputs based upon a user selection. So I don't want to have to put every single possible req.body.whatever in a variable. I'd instead want to just say req.body.all, for example, and save just the data that was submitted to variables, then insert those into the database, extracting the name for each field too, of course.

Answers


You can save the req.body to mongodb directly:

// Submit to the DB
collection.insert(req.body, function (err, data) {
  if (err) {
    res.send("There was a problem adding the information to the database.");
  }
  else {
    res.location("index");
    res.redirect("/");
  }
});

Just persist the req.body object. Keep in mind to filter (delete) some properties like _id:

delete req.body.__id

Need Your Help

How to tell if screen is on with ADB

android testing adb monkeyrunner

I am looking to find out whether or not it is possible to determine if the screen is on on an android device using ADB. I need to know this for some tests I am trying to run using monkey runner. Is...

SQL Server : Islands And Gaps

sql-server sql-server-2008

I'm struggling with an "Islands and Gaps" issue. This is for SQL Server 2008 / 2012 (we have databases on both).