我一直在无休止地研究这个问题,但找不到我正在寻找的简单答案。基本上,我想对数组中的 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,因为我无法找出将存储在数组中的所有子对象作为单个对象批量发布的最佳方法。
有什么建议或最佳做法吗?
最佳答案
如果您将数组作为键发送到您的请求正文中,就像这样
你会得到它作为 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/