Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

node.js - Post Multiple JSON Objects Simultaneously with Express and Postman

I've been researching this question to no-ends, but can't find the simple answer I'm looking for. Basically, I'd like to batch POST JSON objects in array.

I've got a a giant array of JSON objects.

[ 
 {
   "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"
 },
 ...
]

I'm using an Express server that handles post requests looks like this:

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);
  });
});

These objects are then saved in MongoDB as individual records.

I'm using POSTMAN to send HTTP POSTs to my Express Server. As of now, I've been sending all of my JSON POSTS one at a time, because I can't figure out the best way to batch post all the sub-objects stored in the array as individual objects.

Any suggestions or best practices?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you send you array as a key in your request body, something like this

enter image description here

You'll get it as req.body.my_restaurants. Then simply use this :

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

I'm assuming that restaurants is the name of your collection.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...