Tengo relaciones de muchos a muchos para publicaciones y etiquetas.
db.tag.belongsToMany(db.post, { through: 'post_tags', foreignKey: 'tagId', otherKey: 'postId', }) db.post.belongsToMany(db.tag, { through: 'post_tags', foreignKey: 'postId', otherKey: 'tagId', })Estoy tratando de actualizar el contenido de la publicación, incluidas las etiquetas asociadas.
Esto comenzando en la línea 7:
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, }) }) }Yo uso algo muy similar para crear una publicación.
Tenía la esperanza de que esto funcionaría como lo hace para eso.
He leído mucho de los documentos y búsquedas en línea.
En este punto, siento que debe ser algo simple que estoy pasando por alto.
Tal vez incluso una falta de ortografía o una mala ubicación de algo.
He intentado crear datos de respuesta con findByPk como Publicación.
Luego, al ejecutar esto con setTags, sigo teniendo el mismo error.
¿No estoy seguro si tal vez porque Post.update devuelve datos diferentes?
Que hacer Post.create, pensé que leí algo sobre esto.
Pero intenté agregar otro parámetro y no obtuve los resultados esperados.
Si puede ofrecer algún consejo, sería muy apreciado.
¡Gracias!
Llamó a setTags in res , que no es un modelo Sequeize de Post . Primero debe obtener la instancia de Post de esta manera:
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) }) } }) Y recomiendo usar async/await para tener un código de avance en lugar de una cadena de then en este caso:
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, }) } }