Javascript 是否有快捷方式或更短的语法来单独接收req.body的内容?
我想保存req中的author_id,它不是表单的一部分,而是URL中的一个变量参数 目前,我正在分别从req.body和author\u id以及req.user.id添加表单参数,并通过组合上述两个参数创建一个新对象Javascript 是否有快捷方式或更短的语法来单独接收req.body的内容?,javascript,node.js,post,routes,Javascript,Node.js,Post,Routes,我想保存req中的author_id,它不是表单的一部分,而是URL中的一个变量参数 目前,我正在分别从req.body和author\u id以及req.user.id添加表单参数,并通过组合上述两个参数创建一个新对象 router.post("/", middleware.isLoggedIn, function(req, res){ // get data from form and add to campgrounds array var name = req.body.name
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");
}
});
});
我想要一种更短的格式或方法来实现这一点,因为来自req.body的数据将来可能会变得更大&我不想单独提取所有内容并将其与我的作者密钥结合起来。对于ES6,您可以分解结构,并使用速记属性名称:
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 } };
如果不想重复req.body
中的所有非user
属性两次,可以使用类似Lodash的:
使用ES6,您可以分解结构并使用速记属性名称:
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 } };
如果不想重复req.body
中的所有非user
属性两次,可以使用类似Lodash的: