router.route('/vehicles')
.post(function (req, res) {
var vehicle = new Vehicle();
vehicle.make = req.body.make;
vehicle.model = req.body.model;
vehicle.color = req.body.color;
vehicle.save(function (err) {
if (err) {
res.send(err);
}
res.json({message: 'Vehicle was successfully added', make: req.body.make, model: req.body.model, color: req.body.color});
});
})
正如您所看到的那样:make: req.body.make, model: req.body.model, color: req.body.color
我能够成功返回发布的对象。
但是,这不是我需要的,除了返回新创建的对象外,我还需要返回新创建的对象的id。
我该怎么做?
答案 0 :(得分:3)
你可以缩短整个事情:
router.route('/vehicles')
.post(function (req, res) {
var vehicle = new Vehicle(req.body);
vehicle.save(function (err) {
if (err) {
return res.send(err);
}
vehicle.message = 'Vehicle was successfully added';
res.json(vehicle);
});
});
我假设您正在使用mongoose,基于您问题中的其他语法。