4

I have a model which requires a date input in the where clause for a query.

const Model = sequelizeTwo.define('model', {
    A: Sequelize.BIGINT,
    B: Sequelize.DOUBLE,
    C: Sequelize.DOUBLE,
    D: Sequelize.DOUBLE,
    E: Sequelize.DOUBLE, 
    F: Sequelize.DOUBLE,
    DATE: Sequelize.DATEONLY,  
    newCol: Sequelize.VIRTUAL

},{
    tableName: "Model",
    timestamps: false,
    freezeTableName: true
})

DATE here is used as a params for the query to display information on the client. But that is the end of it's use. I don't want to send DATE to the client back but I see no way to remove it.

If i remove it from the model, it gives a timezone error which is another problem as well.

app.get('/api/:date', (req, res) => {
    var date = req.params.date

    Model.findAll({
        where: {
            DATE: {
                [Op.eq]: date
            }
        },
        order: [
            ['A', 'ASC']
        ]
    }).then(result => {

        ...

        for (i; i < result.length; i++) {

            ...
            delete result[i].DATE 
            console.log(result[i].DATE)
            result[i]["newCol"] = values;
        }
        res.json(result);
    })
})

I have tried using the delete operator inside and outside the loop, but it's of no use. It still retains the property and sends it back to the client

            delete result[i].DATE //Inside loop
            delete result.DATE //before loop

The values do they get updated when assignment is done but the property/key can't be modified.

           result[i].DATE = null or undefined

What i want to achieve here is that I just want to send an object back which has all the properties in the sequelize model except DATE

Siddhut
  • 367
  • 6
  • 17

2 Answers2

3

I think you should use excludes feature for this case:

Model.findAll({
    where: {
        DATE: {
            [Op.eq]: date
        }
    },
    order: [
        ['A', 'ASC']
    ],
    attributes: { exclude: ['DATE'] }
})

More information here: sequelize documentation

Oliver Nybo
  • 560
  • 1
  • 6
  • 24
Dat Tran
  • 1,576
  • 1
  • 12
  • 16
0

I think that the best practice is to create another model for the view as a data transfer object (DTO), and to map only the desired properties to it (without the Date).

Further read: DTO.

Pseudocode example:

Model.findAll({
    //...
}).then(result => {

    ...
    let resultDTO = mapToDTO(result);

    res.json(resultDTO);
})
Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91