Search code examples
node.jsmongodbmongoose

Spooky mongoose data save behaviour


I have this code section that will give a "bot access number" that goes from 1 to 3 depeding on user index, but the problem is that when the access number is assigned trough userData.botAccessNumber = <number> I log the number and it works as expected that the numbers goes 1 - 3, but when I do check on mongodb the values are always 3, is there anyway that I can make it work????

users.data.forEach(async user => {
        index++
        const userId = user.id

        let userData = await UserMetrics.findOne({ id: userId })

        let accessNumber = index < 220 ? "1" : index < 440 ? "2" : "3"

        if (userData) {

            userData.followCount = user.public_metrics.following_count
            userData.botAccessNumber = String(accessNumber)

        } else {

            userData = new UserMetrics({
                userName: user.username,
                id: userId,
                followCount: user.public_metrics.following_count,
                botAccessNumber: String(accessNumber)
            })

        }

        await userData.save()
    })

Solution

  • I really don't know the problem source but instead of using a regular for loop (that still have this problem) i just added a await

    for await(const user of users.data){} 
    

    and this solved the problem