1

I want to save the author_id from the req which is not a part of the form instead is one of the variable parameters in URL.

Currently, I am adding the form parameters separately from req.body & author_id from req.user._id & making a new object by combining the above two.

router.post("/", middleware.isLoggedIn, function(req, res){
  // get data from form and add to campgrounds array
  var name = req.body.name;
  var image = req.body.image;
  var desc = req.body.description;
  var author = { //not a part of req.body but I want to add it in new object
      id: req.user._id,
      username: req.user.username
  }
  var price = req.body.price;
    var location = req.body.location;
    var newCampground = {name: name, image: image, description: desc, price: price, author:author, location: location};
    Campground.create(newCampground, function(err, newlyCreated){
        if(err){
            console.log(err);
        } else {
            res.redirect("/campgrounds");
        }
    });
  });

I want a shorter format or way to do this because the data from req.body might get bigger in future & I would not want to extract everything separately & combine it with my author key.

fight_club
  • 327
  • 4
  • 13

1 Answers1

0

With ES6, you can destructure, and use shorthand property names:

const { name, image, description, price, location, user } = req.body;
const author = { id: user._id, username: user._username };
const newCampground = { name, image, description, price, location, author };

// or, without the intermediate `author` variable:

const newCampground = { name, image, description, price, location, author: { id: user._id, username: user._username } };

If you don't want to repeat all the non-user properties in req.body twice, you can use something like Lodash's pick:

const { user } = req.body;
const newCampground = {
  ..._.pick(req.body, ['name', 'image', 'description', 'price', 'location', 'user']),
  author: { id: user._id, username: user._username }
};
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320