Home > Mobile >  Am trying to update a database in sequelize
Am trying to update a database in sequelize

Time:09-28

I am trying to update a sequelize database, where the fields that need to be updated is optional. The problem is that I have 3 fields that need to be updated which are all optional. I do not want to check each field one by one calling update method. Cause that will mean multiple call to the api. Sample raw body input in JSON

{
  "authorIds": [1, 5],
  "tags": ["tech", "health"],
  "text": "Some very short blog post text here."
}

Any of these fields can be optional. This is what I have so far

   const { authorIds, tags, text } = req.body;
     // case where all fields came in
    if (authorIds && tags && text) {
      try {
        const ids = authorIds.join(',');
        const tagValue = tags.join(',');
        await Post.update(
          { authorIds: ids, tags: tagValue, text: text },
          { where: { id: postId } }
        );
      } catch (error) {
        res.json({ error: 'Please check your body format' });
      }
    }

Note I am using SQLite, so I can not store arrays, that why am making the inputs. into string Thanks

CodePudding user response:

You can easily construct an object that you need to pass as the first argument to update dynamically:

if (authorIds || tags || text) {
try {
        const fieldsToUpdate =  {}
        if (authorIds && authorIds.length) {
           const ids = authorIds.join(',');
           fieldsToUpdate.authorIds = ids;
        }
        if (tags && tags.length) {
           const tagValue = tags.join(',');
           fieldsToUpdate.tags = tagValue;
        }
        if (text) {
          fieldsToUpdate.text = text;
        }
        await Post.update(
          fieldsToUpdate,
          { where: { id: postId } }
        );
      } catch (error) {
        res.json({ error: 'Please check your body format' });
      }
}

Also you can try to use object deconstruction along with ternary operators to combine all fields right in the update call.

...(authorIds && authorIds.length ? { authorIds: authorIds.join(',') } : {}).
  • Related