Issue with MongoDB $push within an Array of Arrays: The shorthand property 'elements' does not have a value available in scope

I am encountering an issue while trying to insert data into Elements in MongoDB using TypeScript. Any suggestions on how to resolve this problem?

Attempt 1 Error: I am receiving an error message stating "No value exists in scope for the shorthand property 'elements'. Either declare one or provide an initializer.ts(18004)"

Attempt 1

  async add<T extends { id: string; parentID: string, elementNum: number, name: string, link: string}>(collectionName: string, args: T) {
    const db = await this.getDB();
    const collection = db.collection(collectionName);

    return new Promise((resolve, reject) => {
        collection.updateOne({ id: args.id }, {$push: {elements[args.elementNum]: {id: uuid(), name: args.name, link: args.link, elements: [] }}}, (err, res) => {
          if (err) {
            reject(err);
          }
          resolve(res);
        });
    });
  }

Attempt 2 made changes as follows

    collection.updateOne({ id: args.id }, {$push: {elements: {id: uuid(), name: args.name, link: args.link, elements: [] }}},

Attempt 2 results in Null added at the end

        {
            "id": "1",
            "name": "wk1",
            "iconFile": "icon.png",
            "elements": [
                [
                    {
                        "id": "2",
                        "name": "element2",
                        "link": "https",
                        "elements": [
                            {
                                "id": "1",
                                "name": "element1",
                                "link": "https:"
                            }
                        ]
                    }
                ],
                // other elements and sub-elements
                null,
            ]
        }

My desired outcome is reflected below


        {
            "id": "1",
            "name": "wk1",
            "iconFile": "icon.png",
            "elements": [
                [
                    {
                        "id": "2",
                        "name": "element2",
                        "link": "https",
                        "elements": [
                            {
                                "id": "1",
                                "name": "element1",
                                "link": "https:"
                            }
                        ]
                    },
                    {
                                "id": "newid",
                                "name": "newname",
                                "link": "newlink"
                                "elements":[]
                    }
                ],
                // other elements and sub-elements
            ]
        }

Answer №1

Demo - Check out this live demo on Mongo Playground

Use - Learn how to use the $[] operator in MongoDB

The all positional operator $[] instructs the update operator to modify every element within a specified array field.

The $[] operator is structured as follows:

{ <update operator>: { "<array>.$[]" : value } }

db.collection.update({ _id: 1, "add.id": "1"},
{ $push: { "add.$[].elements": { id: "3", name: "a",  link: "" } } })

If you want to push an array instead of an object, check out this demo - Mongo Playground Array Push Demo

db.collection.update({ _id: 1, "add.id": "1"},
{ $push: { "add.$[].elements": [{ id: "3", name: "a",  link: "" }] } })

const args = {};
args.elementNum = 0;

const update = {
  [`add.$[].elements.${args.elementNum}`]: {
    a: 1
  }
};

console.log(update);

// Use the code above when updating a specific element in the collection

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

Why does the request body show as null even after passing body data in Prisma?

My application uses Prisma for database storage with MySQL. It is built using Next.js and TypeScript. I have set up the API and it is functioning properly. However, when I try to save data sent through the API, the `request.body` is null. Interestingly, wh ...

Tips for managing several mongodb databases on a remote server

My server on CentOS is accessed remotely via SSH and currently has a test MongoDB database running on port 27017. I am interested in setting up additional databases either on the same port or on a different port to allow for simultaneous use of two databa ...

Issue with rendering React Toastify

I'm running into an issue while trying to integrate react toastify into my react vite application. Specifically, I keep getting an error related to useSyncExternalStore even after attempting to switch to version 9 of react toastify. My React version i ...

Guiding user to their destination after signing in

Having trouble showing different headers based on user login status? Users can log in using login.php, but you're struggling to display header.php when a user is not logged in or logged in. You want the page to show profile form content when they are ...

What is the correct way to set up a custom class instance with specific parameters at the top level?

Is it possible to utilize the defineString(), defineInt, ... functions within a top-level custom class constructor? defineString() returns a StringParam object which has a value() method. I am looking to use parameterized configuration to initialize an in ...

Tips for Guaranteeing a Distinct Email and Username are Stored in MongoDB with Mongoose

db.UserSchema = new db.Schema({ user: {type:String, unique:true, required:true,index:true}, email: {type:String, unique:true, required:true,index:true}, password: {type:String, required:true}, phon ...

Choose only the options that are present in both arrays

I am working on creating a multiple select feature that displays all nodes, but only checks the ones that are present in 2 arrays. My front end is developed using Angular 8 and TypeScript. private mountSelect(nodesInRelation, lineApiKey) { console.lo ...

The function 'sendEmailVerification' is not a property of the type 'Promise<User>'

Hey there, I've been working on my ionic4 app and have encountered an issue with the sendEmailVerification function. The console is suggesting that I may have forgotten to use 'await'. Any ideas on how to resolve this? Thank you. import { In ...

The Rxjs `of` operator fails to emit a value when utilizing proxies

I ran into an issue with a basic unit test that utilizes Substitute.js (I also tried using TypeMoq mocks, but encountered the same behavior). My test simply tries to use the of operator to emit the mocked object. Surprisingly, without any additional opera ...

What allows the execution of "T[keyof T] extends Function" in TypeScript specifically for Strings?

Lately, I've been experimenting with type changes and I find myself puzzled when encountering code like the following: type DeepReadonly<T> = { readonly [k in keyof T]: T[k] extends Function?T[k]:DeepReadonly<T[k]> } // Let's defin ...

issue encountered while adding a new element to an array using javascript

I am encountering an issue with adding comments from HTML form elements to an array in AngularJS. Whenever I try to use the Javascript push function, I receive an error stating "property of object doesn't exist". Can someone assist me in resolving thi ...

Update the field 'payments._id' in MongoDB to a timestamp

I need to change the value of 'payments._id' to a timestamp. In MongoDB, the 'payments._id' object is automatically generated when inserting a document into the collection. onMounted(async () => { const res = await axios.get(" ...

Creating a TypeScript library with Webpack without bundling may seem like a daunting task, but

Currently, I am developing a React component package using Typescript and NPM. During my research, I discovered that generating individual .js and .d.ts files is more beneficial than bundling them into one bundle.js file. However, I am facing difficulty in ...

Create dynamic modals in ReactJS that appear when a row is clicked

Engaged in a project for an undisclosed entity where patient data is retrieved from their API and displayed as modal on the page. Clicking on a modal reveals more threat information in another modal. The objective is for these modals to render based on a c ...

Improved ergonomics for enhancing TypeScript union-narrowing typeguard function

Within our codebase, we have a utility that generates a typeguard to narrow down a discriminated union: export type ExtractBranchFromUnion< UNION, DISCRIMINANT extends keyof UNION, BRANCH extends UNION[DISCRIMINANT], > = UNION extends Record< ...

Using TypeScript to call a class method from within another function

Currently, I am working on an Angular 2 application and struggling to grasp the concept of TypeScript's this scope. Within my TypeScript class named SharedService, there is a function called handleError. If this function encounters a 401 status, I wa ...

There is an issue with the Angular Delete request functionality, however, Postman appears to be

HttpService delete<T>(url: string): Observable<T> { return this.httpClient.delete<T>(`${url}`); } SettingsService deleteTeamMember(companyId: number, userId: number): Observable<void> { return this.httpService.delete< ...

Creating a merged object from a split string array in TypeScript

I possess an array containing objects structured as follows; const arr1 = [ {"name": "System.Level" }, {"name": "System.Status" }, {"name": "System.Status:*" }, {"name": "System.Status:Rejected" }, {"name": "System.Status:Updated" } ] My object ...

Searching for a sub-document within a Mongoose database by using a string identifier

In my database, I have set up the following schema: var invitationSchema = new Schema({ emailAddress : String }); var eventSchema = new Schema({ name : String, start_date : Date, end_date : Date, venue : { type : Schema.ObjectId, ref ...

What is the specific purpose of the 'extend' keyword in Typescript?

Recently, I have been delving into the realm of Javascript/Typescript/React as a PHP developer. During my learning process, I encountered a few perplexing issues that I could not fully grasp. In light of this, I am reaching out to the experienced indiv ...