【问题标题】:Node.js: extracting data from form and submitting to Mongo dbNode.js:从表单中提取数据并提交到 Mongo db
【发布时间】:2014-01-28 15:11:29
【问题描述】:

使用 Node 和 Express。我将如何将所有 request 数据保存到数组中,然后将数组中的每个项目插入到 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.whatever 放在一个变量中。例如,我只想说req.body.all,只保存提交给变量的数据,然后将它们插入数据库,当然也提取每个字段的名称。

【问题讨论】:

    标签: javascript node.js mongodb express


    【解决方案1】:

    您可以直接将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 对象。请记住过滤(删除)一些属性,例如_id

    delete req.body.__id
    

    【讨论】:

    • 哦,太好了,谢谢!不过很好奇,我有什么理由要删除 id 吗?
    • 您可能需要删除_id 字段以避免恶意用户将数据发布到您的处理程序,在某些情况下可能会更改现有文档。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2012-01-27
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    相关资源
    最近更新 更多