Javascript Node.js:从表单中提取数据并提交给Mongo db

Javascript Node.js:从表单中提取数据并提交给Mongo db,javascript,node.js,mongodb,express,Javascript,Node.js,Mongodb,Express,使用Node和Express。如何将所有请求数据保存到数组中,然后将数组中的每个项插入到mongo集合中 我的路线当前设置如下:app.post(“/addbulletin”,routes.addbulletin(db)) 我正在处理视图和数据,如下所示: exports.addbulletin = function(db) { return function(req, res) { // Get our form values. These rely on the "name"

使用Node和Express。如何将所有
请求
数据保存到数组中,然后将数组中的每个项插入到mongo集合中

我的路线当前设置如下:
app.post(“/addbulletin”,routes.addbulletin(db))

我正在处理视图和数据,如下所示:

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("/");
      }
    });

  }
}

这种方式的问题是,我必须知道需要发送到数据库的所有项目。如果我不知道页面上有哪些字段可以从中获取数据,该怎么办?这正是我目前所处的情况,因为我有一个表单,它根据用户选择填充输入。所以我不想把每一个可能的
req.body.which
都放在一个变量中。例如,我只想说
req.body.all
,只保存提交给变量的数据,然后将这些数据插入数据库,当然也提取每个字段的名称

您可以将
req.body
直接保存到mongodb:

// 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("/");
  }
});
只需持久化req.body对象。请记住筛选(删除)某些属性,如
\u id

delete req.body.__id

哦,很好,谢谢你!但奇怪的是,我想删除id有什么原因吗?您可能想删除
\u id
字段,以避免恶意用户向您的处理程序发布数据,在某些情况下可能会更改现有文档。