kroe761
kroe761

Reputation: 3534

How to remove json elements from response after sequelize creates a db record?

Using sequelize, I can create a product in my database using the Product modek, but I want to edit the json response, removing the updatedAt and createdAt elements. How would I do this?

My code:

router.post('/products', (req, res, next) => {
    Product.create({
        name: req.body.name,
        price: req.body.price
    }).then(
        product => res.status(200)
            .json(product)
    )
});

When calling localhost:3000/products with this body:

{
    "name": "A Book",
    "price": 10.99,
}

I get this in response:

{
    "id": 8,
    "name": "A Book",
    "price": 10.99,
    "updatedAt": "2018-06-26T20:09:38.643Z",  <-- Remove?
    "createdAt": "2018-06-26T20:09:38.643Z"   <-- Remove?
}

Upvotes: 0

Views: 218

Answers (1)

Praveenkumar Kalidass
Praveenkumar Kalidass

Reputation: 429

Try using lodash pick().

If your response is,

{
    "id": 8,
    "name": "A Book",
    "price": 10.99,
    "updatedAt": "2018-06-26T20:09:38.643Z",
    "createdAt": "2018-06-26T20:09:38.643Z"
}

Try, var result = _.pick(response, ["name", "price"]);

router.post('/products', (req, res, next) => {
    Product.create({
        name: req.body.name,
        price: req.body.price
    }).then(
        product => 
            var result = _.pick(response, ["name", "price"]);
            res.status(200).json(result)
    )
});

Upvotes: 1

Related Questions