英文:
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 = <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()
})
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论