Rosenberg
Rosenberg

Reputation: 2444

Return object created on POST - express.js

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

As you can see by adding this: make: req.body.make, model: req.body.model, color: req.body.color I was able to successfully return the posted object.

However, that's not quite what I need, besides returning the newly created object I also need to return the id of the newly created object.

How can I do this?

Upvotes: 1

Views: 2147

Answers (1)

Paul
Paul

Reputation: 36319

You can shorten the whole thing like so:

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

I'm assuming you're using mongoose, based on the other syntax in your question.

Upvotes: 3

Related Questions