Adding a fresh attribute to MongoDB using push model

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

Answer №1

Resolved: The primary issue stemmed from using models as microservices without properly adding a new field in the .js file.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for importing the TokenExpiredError that is thrown by the verify function in jsonwebtoken?

Is there a way to determine if an Error object thrown by the jwt.verify function in the jsonwebtoken library is of type TokenExpiredError using Typescript's instanceof? For example: import jwt from "jsonwebtoken"; function someFunction() { try { ...

Leveraging ES6 Symbols in Typescript applications

Attempting to execute the following simple line of code: let INJECTION_KEY = Symbol.for('injection') However, I consistently encounter the error: Cannot find name 'Symbol'. Since I am new to TypeScript, I am unsure if there is somet ...

Saving sub-documents does not automatically update the parent document

I'm currently exploring the dynamics of relationships in mongoose. My setup involves two models: a parent and a child. var childrenSchema = new Schema({ name : String, date : {type : Date, default: Date.now}, attribute1 : String, attr ...

What is the best way to include a non-data custom attribute in a TSX template without any value?

Currently, I am working on a React component with Typescript. The initial code looks like this.... const NameFormatter = React.createClass({ render() { return ( <div> <div className="dataset-name"> ...

Exploring the world of child routing in Angular 17

I've been experimenting with child routing in Angular and encountered some confusion. Can someone explain the difference between the following two routing configurations? {path:'products',component:ProductsComponent,children:[{path:'de ...

Executing Typescript build process in VSCode on Windows 10 using Windows Subsystem for Linux

My configuration for VSCode (workspace settings in my case) is set up to utilize bash as the primary terminal: { "terminal.integrated.shell.windows": "C:\\WINDOWS\\Sysnative\\bash.exe" } This setup allo ...

Unable to log in with password after hashing using React, NodeJS, and mySQL

I've implemented a salt and hash function to secure my password. Strange thing is, I can't log in using the original password, but it works when I use the hashed password from the database. Salt: "HashedPasswordCheck" Hash Function: function has ...

Incorporating Moralis into Ionic Angular with TypeScript

I'm currently developing an app using Ionic Angular (TypeScript) that will be compatible with both Android and iOS devices. I've decided to incorporate the Moralis SDK to establish a connection with the Metamask wallet. Here's a summary of ...

Typescript's puzzling selection of the incorrect overload

I have a method structured as shown below: class Bar { public executeInWorker(cb: () => void): void; public executeInWorker(cb: () => Promise<void>): void | Promise<void>; public executeInWorker(cb: () => void | Promise< ...

Issue: Unable to set headers after a session has been initiated

I encounter an issue after navigating a few times with the session started by the page. It gives me an error stating that headers cannot be sent after they are sent until I delete the cookie from the session. This problem has persisted for several days, an ...

How can I update a dropdown menu depending on the selection made in another dropdown using Angular

I am trying to dynamically change the options in one dropdown based on the selection made in another dropdown. ts.file Countries: Array<any> = [ { name: '1st of the month', states: [ {name: '16th of the month&apos ...

Identifying data types in arrays using TypeScript type predicates

My current approach involves a function that validates if a variable is an object and not null: function isRecord(input: any): input is Record<string, any> { return input !== null && typeof input === 'object'; } This type predica ...

Enhance your React Native experience with IntelliSense recommending react-native/types over react-native

I am trying to bring in <View from react-native, but instead, I am getting react-native/types How can I resolve this issue? This is a new project starting from scratch and I followed the documentation by adding TypeScript as instructed: yarn add --dev ...

Show all span elements in a map except for the last one

Within my ReactJS application, I have implemented a mapping function to iterate through an Object. In between each element generated from the mapping process, I am including a span containing a simple care symbol. The following code snippet demonstrates t ...

Why do my messages from BehaviorSubject get duplicated every time a new message is received?

Currently, I am using BehaviorSubject to receive data and also utilizing websockets, although the websocket functionality is not relevant at this moment. The main issue I am facing is why I keep receiving duplicated messages from BehaviorSubject. When exa ...

Searching for the initial subdocument that matches a query in MongoDB

After following a documentation on time series data, I have designed a database schema that closely resembles the example provided here. This resulted in the creation of documents like the one below: { "_id" : "unique_name_1", "data" : { ...

Combine multiple objects to create a new object that represents the intersection of all properties

Imagine you have these three objects: const obj = { name: 'bob', }; const obj2 = { foo: 'bar', }; const obj3 = { fizz: 'buzz', }; A simple merge function has been written to combine these three objects into one: ...

Verify that each field in the form contains a distinct value

I have a formarray with nested formgroups. How do I ensure that the elements within each formgroup are unique? Here is an example of my form setup: form: FormGroup = this.formBuilder.group({ fields: this.formBuilder.array([]), }); private createField() ...

What factors may be influencing the incorrect behavior of this simple code when using useState()?

In an attempt to replicate a problem I encountered in a larger project component, I have created a simple component. Let's consider the scenario where we have an arrayA and we want to add the value 1 to it on each button click, while also updating ano ...

Astro component experiencing script tag malfunction within content collection

I'm trying to create something using a script tag, but for some reason the script doesn't seem to be working properly. Below is my content collection: --- title: Essay Similarity stakeholder: THESIS articleDate: 05 Feb 2023 projectStart: 2022-08 ...