sequelize创建数据库记录后如何从响应中删除json元素?

时间:2018-06-26 20:15:33

标签: express sequelize.js

使用sequelize,我可以使用product模式在数据库中创建一个Product,但是我想编辑json响应,删除了updatedAt和createdAt元素。我该怎么办?

我的代码:

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

使用此主体调用localhost:3000 / products时:

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

我得到这个回应:

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

1 个答案:

答案 0 :(得分:1)

尝试使用lodash pick()。

如果您的答复是

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

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