Is it possible to get only values of sequelize attribute?

Viewed 4365

I'm trying to figure how can i get an array of only the values without the keys of an attribute in sequelize ORM with no other constant making things like attribute.value.

Now i have this as instance method inside a model:

Event.getDate = function (id) {
  return this.findOne({
    where: {
      [Op.or]: [
        { homeId: { [Op.eq]: id } },
        { awayId: { [Op.eq]: id } }
      ],
      status: { [Op.eq]: 'FINISHED' }
    },
    order: [[sequelize.col('date'), 'DESC']],
    attributes: ['date']
  })
}

that's return [date: 1/10/2019],

it is possible to get something like 1/10/2019 inside the query?

1 Answers

Your query isn't returning [date: 1/10/2019] it is returning an Instance of the Event Model with only the date attribute populated, and when you convert to a string you see the value. It should also be { "date": "1/10/2019" } with curly braces as it is an object, not an array.

Sequelize will always return an object or an array of objects, not an array of values. You can easily convert to just the values accessing the property or using Array.map(). By passing raw: true to the query it will also return plain JSON instead of Model Instances which is more performant if you don't need to use any of the instance functions.

const event = await Event.findOne({
  where: {
    [Op.or]: [
      { homeId: { [Op.eq]: id } },
      { awayId: { [Op.eq]: id } }
    ],
    status: { [Op.eq]: 'FINISHED' }
  },
  order: [[sequelize.col('date'), 'DESC']],
  attributes: ['date'],
  raw: true,
});

return event.date;

Or if you were to use findAll() and get back an array...

const events = await Event.findAll({
  where: {
    [Op.or]: [
      { homeId: { [Op.eq]: id } },
      { awayId: { [Op.eq]: id } }
    ],
    status: { [Op.eq]: 'FINISHED' }
  },
  order: [[sequelize.col('date'), 'DESC']],
  attributes: ['date'],
  raw: true,
});

return events.map((event) => event.date);
Related