I wrote a basic script that calculates the number of documents for a specific user and assigns it to externalUser.totalIcons
. However, when I try to execute it, the model is not saved and the new property is not added to the database.
My question is: where did I go wrong in my script and how can I fix it to ensure the changes are reflected in the database?
import { Icon, User } from '../../models'
import { runScript } from '../utils'
export async function run () {
const userCriteria = { isExternal: true }
const iconCriteria = { 'icons.source': 'external' }
const externalUsers = await User.find(userCriteria)
for (const externalUser of externalUsers) {
externalUser.totalIcons = await Icon.countDocuments({
...iconCriteria,
'icons.userId': externalUser._id
})
console.log(externalUser._id + ' has: ' + externalUser.totalIcons)
await externalUser.save()
}
}
if (require.main === module) {
runScript('totalIconsFieldUpdate', run)
}