Append element into array of objects

Hello everybody,

I’m trying to insert (append) a new object inside an array of object elements.

This is the piece of code that issues the update:

setUserBrand(id:string,ruolo:string){

      const mongodb = this.app.currentUser!.mongoClient("mongodb-atlas")

      const users = mongodb.db("Saw").collection<any>("Users");

      const NEW_RUOLO = {

        "brand":new Realm.BSON.ObjectId(this.getActiveBrandId()),

        "ruolo":ruolo

      }

      const query = { 

        "_id":new Realm.BSON.ObjectId(id)

       };

       

      const update = {

        $push: {

          "ruoli":NEW_RUOLO

        }

      };

      const options = { upsert: false,

        'Content-Type': 'application/json',

        "Authorization": "Bearer "+this.getAccessToken()

      };

      return users.updateOne(query, update, options);

  }

The schema of the Users collection is the following:

image

I would like to append to the array “ruoli” a new object, but the piece of code written above does not work.

Have you any idea why that does not work? Thank you!

The problem was that the “ruolo” field was not a string, so adding the .toString() I resolved the problem.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.