幽灵獴数据保存行为

huangapple go评论66阅读模式
英文:

Spooky mongoose data save behaviour

问题

我有这段代码部分,它将根据用户索引提供一个“机器人访问号”,从1到3,但问题在于当通过userData.botAccessNumber = <number>分配访问号时,我记录了该号码,它按预期工作,数字为1至3,但当我在mongodb上检查值时,值始终为3,是否有办法可以使它正常工作?

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()
})
英文:

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 = &lt;number&gt; 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 =&gt; {
        index++
        const userId = user.id

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

        let accessNumber = index &lt; 220 ? &quot;1&quot; : index &lt; 440 ? &quot;2&quot; : &quot;3&quot;

        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()
    })

答案1

得分: 0

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

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

and this solved the problem.

英文:

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

huangapple
  • 本文由 发表于 2023年3月31日 23:42:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75900403.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定