Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
Sequelize - .update - setTags is not a function

"setTags is not a function"

I have Many-to-Many relationships for Posts and Tags.

db.tag.belongsToMany(db.post, {
  through: 'post_tags',
  foreignKey: 'tagId',
  otherKey: 'postId',
})
db.post.belongsToMany(db.tag, {
  through: 'post_tags',
  foreignKey: 'postId',
  otherKey: 'tagId',
})

I'm trying to update the Post's content, including the associated Tags.


This beginning at line 7:

  • Check for tags
  • Match found tags
  • Set the tags of post

exports.update = (req, res) => {
      const id = req.params.id
      Post.update(req.body, {
        where: { id: id },
      })
        .then((number) => {
          if (req.body.tags) {
            Tag.findAll({
              where: {
                name: {
                  [Op.or]: req.body.tags,
                },
              },
            }).then((tag_items) => {
              res.setTags(tag_items)
            })
          }
          if (number == 1) {
            res.send({
              message: 'This post attempt was successful.',
            })
          } else {
            res.send({
              message: `Problem with updating id=${id}. May not exist, or req.body could be empty!`,
            })
          }
        })
        .catch((err) => {
          res.status(500).send({
            message: 'There was an error updating post id=' + id,
          })
        })
    }

I use something very similar for creating a Post.

I was hoping this would work like how it does for that.

I have read so much of the documents and online searches.

At this point I feel like it must be something simple I'm overlooking.

Maybe even a misspelling, or bad positioning of something.


I have tried creating response data with findByPk as the Post.

Then running this with setTags, I still get the same error.

Not sure if maybe because Post.update returns different data?

Than doing Post.create, I thought I read something on this.

But I had tried adding another parameter and wasn't getting expected results.


If you can offer any advice, it would be greatly appreciated.

Thank you!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You called setTags in res which is not a Sequeize model of Post. You need to get Post instance first like this:

 Post.findOne({
        where: { id: id },
      }).then((post) => {
if (req.body.tags) {
            Tag.findAll({
              where: {
                name: {
                  [Op.or]: req.body.tags,
                },
              },
            }).then((tag_items) => {
              post.setTags(tag_items)
            })
          }  
})

And I recommend to use async/await to have straint-forward code instead of chain of then in this case:

exports.update = async (req, res) => {
      const id = req.params.id
   try {
      const number = await Post.update(req.body, {
        where: { id: id },
      })
      if (req.body.tags) {
        const post = await Post.findOne({
          where: { id: id },
        })
        const tag_items = await Tag.findAll({
           where: {
             name: {
               [Op.or]: req.body.tags,
             },
          });
          post.setTags(tag_items)
      }
      if (number == 1) {
         res.send({
           message: 'This post attempt was successful.',
         })
      } else {
         res.send({
           message: `Problem with updating id=${id}. May not exist, or req.body could be empty!`,
         })
      }
  } catch((err) {
       res.status(500).send({
         message: 'There was an error updating post id=' + id,
       })
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda