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

我一直在研究这个问题没有结束,但找不到我正在寻找的简单答案。 基本上,我想在数组中批量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); }); }); 

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

我使用POSTMAN将HTTP POST发送到我的Express服务器。 到目前为止,我一直在发送所有的JSON POSTS,因为我无法弄清楚将所有存储在数组中的子对象作为单个对象进行批处理的最佳方式。

任何build议或最佳做法?

如果你发送你的数组作为一个键在你的请求正文,这样的事情

在这里输入图像说明

你会得到它作为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"); }); 

我假设餐馆是你collections的名字。

我一直在玩以前的解决scheme,我标记为正确的。 比使用.insertMany()函数更好的方法是使用.create()函数。

.insertMany()函数跳过与.save()相关的中间件,而create()函数使用相同的过程,但也可以处理数组。

所以我修改的快速路由看起来像下面(其中Organization是我的架构的名称):

 app.post('/api/orgs', function(req, res) { // Array of JSON Objects if (req.body.batch){ Organization.create(req.body.batch, function(err){ if(err) res.send(err); else res.json(req.body); }); } // Single JSON Object else { 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 else res.json(req.body); }); } }); 

我发送的JSON对象如下所示:

JSON在POSTMAN

希望这可以帮助其他人。