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

Ahm*_*que 3 post json mongodb node.js 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"
 },
 ...
]
Run Code Online (Sandbox Code Playgroud)

我正在使用处理发布请求的 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);
  });
});
Run Code Online (Sandbox Code Playgroud)

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

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

有什么建议或最佳实践吗?

Sid*_*era 5

如果您将数组作为请求正文中的键发送,如下所示

在此输入图像描述

您将获得 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");
});
Run Code Online (Sandbox Code Playgroud)

我假设餐馆是您的集合的名称。