简体   繁体   中英

Mongoose update map element inside array of document

as the title says, I want to update a value in a map inside an array in a document, Im using Mongoose. This is for a Discord bot, basically adding exp to a char every time user does a command, and it works, but it doesn't look right and I've been told it doesn't work sometimes:

This is how the maps inside the array look like: click

// This gets the user document
let user = bot.userinventories.findOne({ userID: message.author.id })
// This searches the specific map I need by name
let check = await user.get('characters').filter(char => char.name === user.get('leveling'));

        // This modifies the map in only 1 value
        check[0].exp++;
        // This removes the entire map and saves it again
        await bot.userinventories.updateOne({ userID: message.author.id }, 
            { $pull: 
                { 
                characters:  { name: check[0].name }
                }
            })
        await bot.userinventories.updateOne({ userID: message.author.id }, 
                { $push: 
                    { 
                        characters: check[0]
                    }
            })

As you can see, the part that doesn't seem right is having to entirely remove the map before saving it again, this also breaks any order by date. The big problem is that users have told me they've lost characters to this. Another thing that sometimes fails is the 'let check' line, even tho it finds a map by the exact name (because of my code) it fails randomly like 1/20 times.

I found this which works, even tho it stills moves the object to the last place of the map, but it seems cleaner than what I had:

await bot.userinventories.updateOne(
            { userID: message.author.id, "characters.name": check[0].name },
            { $set: { "characters.$.exp" : check[0].exp } }
        )

Edit: for it to not move the edited object to last place, I had to make a new variable or not use a variable for '"characters.$.exp" : ' for some reason

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