Home > front end >  How to format Sequelize response as array of strings instead of objects
How to format Sequelize response as array of strings instead of objects

Time:12-22

I'm using Sequelize on a join query. Currently, the data from the join table is presented as an array of objects. The client expects an array of strings.

Is this something that can / should be done with Sequelize? Should I transform the data manually before sending it to the client?

Query

movie.findOne({
        include: [
          {
            model: db.genre,
            attributes: ['name'],
            through: {
              attributes: [],
            },
          },
      })

Output

{
  "id": 52,
  "type": "movie",
  "Genres": [
      {
          "name": "Action"
      },
      {
          "name": "Comedy"
      }
  ]
}

Ideally, I would like Genres to be formatted as:

"Genres": ["Action", "Comedy"]

CodePudding user response:

Not technically possible with pure sequelize. It is trivial to format the object after the query though.

ob.Genres = ob.Genres.map(x=>x.name);
 // { id: 52, type: 'movie', Genres: [ 'Action', 'Comedy' ] }

And you can also technically use a sequelize literal to group what you need together as a separate attribute- but it is comically more complex than necessary.

movie.findOne({
    where:{
        id:52
    },
    attributes: [
            'id','type',
            [Sequelize.literal(`
                (
                SELECT GROUP_CONCAT(name)
                    FROM Genres
                    WHERE
                        movieId = 52
                )`), 'Genres'],
            ] 
})

Making some assumptions with your database, but that's the idea. You can GROUP_CONCAT all the names from the results of a query and put them into a new attribute.

I would suggest just mapping the value manually after querying.

CodePudding user response:

you can use the pluck method provided by Sequelize to achieve the same result. The pluck method allows you to specify the property you want to extract from each object in the array and returns an array of those values.

const response = movie.findOne({
    include: [
      {
        model: db.genre,
        attributes: ['name'],
        through: {
          attributes: [],
        },
      },
  });

  const stringsArray = response.map(object => object.property);
  console.log(stringsArray);
  • Related