简体   繁体   中英

how to update a mysql json array using nodejs

I am using mysql 5.6 and as a result dont have access to existing JSON functions in mysql - so looking for some clever workaround ideas...

I have a Story table in my mysql database that has a field called "tags". Tags is just a string field stores a JSON array of tagIds eg [2,5,6] which relate back to another table called tag. This allows me to easily reconstruct tag information in my UI by combing the json array and the tag data.

However now I need to update those tags in the database and its proving challenging. For example if I want to delete a tag with id = 6 I then need to remove it from all the places its referenced in stories ie

update story set tags = {new tag list excluding 6} where tags used to contain 6

I am unsure how to correctly work with these JSON blobs in mysql.

Likewise in some cases I want to replace a tag with another tag id, ie

update story set tags = {new tag list excluding 6 and including new tag id} where tags used to contain 6

I could retrieve them all and do individual processing from within the server ie Nodejs and update each record individually but seems very inefficient.

What is the correct or desired approach here?

The "correct" approach would be to create another table story_tags (id, tag_id, story_id) with one-to-many relationship with story table. Then you could simply do:

select tag_id from story_tags were story_id = xx

and

delete from story_tags were tag_id = xx

However, this requires redesigning the data model of your app.

A less optimal approach is to create a class handling the tag logic in your app in the way you described it. For this solution, you need to assess how often updates/deletes happen and how significant drop on performance is acceptable. A scan/update of a few thousand rows at the time should not have a too severe impact on overall performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM