json - 使用 Express 和 Postman 同时发布多个 JSON 对象

标签 json node.js mongodb post express

我一直在无休止地研究这个问题,但找不到我正在寻找的简单答案。基本上,我想对数组中的 POST JSON 对象进行批处理。

我有一个巨大的 JSON 对象数组。

[ 
 {
   "Name": "SEARCH Resource Center",
    "Address": "2505 Fannin St, Houston, TX 77002",
    "Phone": "(713) 739-7752",
    "Hours": "Mon-Fri, 8am to 3pm",
    "Category": "Drop-In Centers"
 },
 {
   "Name": "Salvation Army Social Services - Young Adult Resource Center",
   "Address": "2208 Main St, Houston, TX 77002",
   "Phone": "(713) 658-9205",
   "Hours": "Mon-Thurs, 11am to 3pm",
   "Category": "Drop-In Centers"
 },
 ...
]

我正在使用处理发布请求的 Express 服务器,如下所示:

app.post('/api/orgs', function(req, res) {

  // Creates a new User based on the Mongoose schema and the post body
  var newOrg = new Organization(req.body);

  // New User is saved in the db.
  newOrg.save(function(err){
    if(err)
      res.send(err);

    // If no errors are found, it responds with a JSON of the new user
    res.json(req.body);
  });
});

然后这些对象作为单独的记录保存在 MongoDB 中。

我正在使用 POSTMAN 将 HTTP POST 发送到我的 Express 服务器。截至目前,我一直在一次发送我所有的 JSON POST,因为我无法找出将存储在数组中的所有子对象作为单个对象批量发布的最佳方法。

有什么建议或最佳做法吗?

最佳答案

如果您将数组作为键发送到您的请求正文中,就像这样

enter image description here

你会得到它作为 req.body.my_restaurants。然后简单地使用这个:

db.collection('restaurants').insertMany(req.body.my_restaurants, function(err, restaurants){
    if(err) console.log(err);
    else console.log("restaurants Added Successfully");
});

我假设 restaurants 是您收藏的名称。

关于json - 使用 Express 和 Postman 同时发布多个 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35488386/

相关文章:

javascript - 来自 Web 服务的 JSON 响应 - 最佳实践问题

将 CSV 转换为 GeoJSON 的 Python 脚本

node.js - gridfs-stream 和 mongoose >= 4.11.0 连接设置

javascript - 通过命令行将 node.js 与无浏览器 jQuery 结合使用

javascript - ejs 表单重定向到 URL 的双份副本(express.js)

node.js - 将 MongoDB View 合并到 Node 中

javascript - 在 Javascript 中将 JSON 转换为 HTML

javascript - 无法解析 Json 文件

node.js - 我想更新用户个人资料

mongodb - 字段名称中未捕获的异常 : can't have .