Mongodb (Mongoose) does not update properties of an object array type document

Asked

Viewed 13 times

0

I have a 'document' of users that has a tag field of type Array that receives objects, these objects are posting tags that store all tags used by it and the amount of repetitions. The problem is that I do all the logic to update Count, create a new object, it’s all right, but when I step into mongoDB it doesn’t update. With the same code I can add new objects, delete, and even reset to an empty array, Mongodb updates everything, but does not update if I try a specific field type user.tags[0].count = 5 pu even if I create an entire object and replace it, it adds the new data but ignores the changes user.tags = newTags.

I am using Nodejs.

My schema model:

const mongoose = require('mongoose')

const modelSchema = new mongoose.Schema({
    name: { type: String, required: true, trim: true, min: 3, max: 60 },
    tags: { type: Array }
})
const modelName = 'users'

//Verifica se uma conexão já esta aberta, se sim então usa a mesma
if (mongoose.connection && mongoose.connection.models[modelName]) {
    module.exports = mongoose.connection.models[modelName]
} else {
    module.exports = mongoose.model(modelName, modelSchema)
}

Code logic, but even if the FOR is wrong, yet this is not the focus, because even if I try to change directly without all this code, it still doesn’t work.

const userDB = require('../models/user')
...
        const user = await userDB.find({name: 'exemplo'})
        let copyTags = [...user.tags]

        /** data.tags é o array de tags que recebo na requisição */
        for (let i = 0; i < data.tags.length; i++) {
            /** depois de percorrer o segundo for, status diz se encontrou tags ou nao */
            let status = false 
        
            for (let y = 0; y < copyTags.length; y++) {
                if (data.tags[i] == copyTags[y].text) {
                    copyTags[y].count = copyTags[y].count + 1
                    status = true
                }
            }

            /** Se o não econtrou tags então adiciona um novo objeto no array de tags*/
            if (!status) {
                copyTags.push({ text: data.tag[i], count: 0 })
            }
        }

        /** console.log(copyTags) aqui mostra que as tags repetidas tiveram icremento no count*/
        user.tags = copyTags
        /** console.log(user) aqui mostra que user.tags foi atualizado com sucesso */
        await user.save()

To conclude I leave a practical example: A user who has no tags and is informed this array ['java', 'Node', 'React']. Giving a console.log copyTags before saving this is the result (but not in JSON). So I see that this right and do user.tags = copyTags, and it works. The database saves the same array.

[
   {"text":"java", "count": 0},
   {"text":"node", "count": 0},
   {"text":"react", "count": 0}
]

Now when repeating the request with the same tags and giving a console.log this time have:

[
   {"text":"java", "count": 1},
   {"text":"node", "count": 1},
   {"text":"react", "count": 1}
]

Then as programmed this new array is added to the user but this time even showing the new values mongodb keeps everything at 0 (zero).

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.