Home > Net >  Push model with new property to MongoDB
Push model with new property to MongoDB

Time:09-28

I have a simple script that counts the number of documents of a particular user and assigns it to externalUser.totalIcons and after that saves this model to the database (MongoDB).

But when I'm trying to run it, it does not save the model and does not add a new property to the database.

Question: where I messed up something and what workaround can I apply here to see that script updated it 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)
}

CodePudding user response:

Solved: So the main problem was that I had models as microservices and I did not build it up to get a new field activated in .js file

  • Related