Post Multiple JSON Objects Simultaneously with Express and Postman

前端 未结 2 874
故里飘歌
故里飘歌 2020-12-17 05:17

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

相关标签:
2条回答
  • 2020-12-17 05:55

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

    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.

    0 讨论(0)
  • 2020-12-17 05:59

    I've been playing with the previous solution I marked as correct. An even better approach than using the .insertMany() function is to use the .create() function.

    The .insertMany() function skips the middleware associated with .save(), whereas the create() function uses the same process, but can also handle arrays.

    So my modified express route looked like the below (where Organization is the name of my schema):

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

    And I'm sending JSON objects that look like:

    Hope this helps someone else down the line.

    0 讨论(0)
提交回复
热议问题