skip to Main Content

I need to add a ref in my array using $addToSet.

It’s my schema

  @Allow()  
  @ApiProperty(GatewaySchemaSwagger.API_PROP_ADMIN_ID)
  @Prop({required: true, type: [MongooseSchema.Types.ObjectId] , ref: 'User' })
  admin: [User];

it’s my collection

{
"_id" : ObjectId("63c022bfd2d744ebaffe3412"),
"buttons" : [],
"admin" : [ 
    ObjectId("636bc633ccc1e71aa32ad831")
],
"user" : ObjectId("636bc633ccc1e71aa32ad831"),
"channelId" : "1",    
}

It’s my update

let findUser = await this.usersService.findByEmail(data.email);
await this.GatewayModel.findOneAndUpdate({ admin: userId, channelId: channelId }, { $addtoSet: { "admin": [findUser._id]  } })

My error is:

Unknown modifier: $addtoSet. Expected a valid update modifier or
pipeline-style update specified as an array

2

Answers


  1. Chosen as BEST ANSWER

    How I modified and it works now.

    Schema:

      @Allow()  
      @ApiProperty(GatewaySchemaSwagger.API_PROP_ADMIN_ID)
      @Prop({required: true, type: [MongooseSchema.Types.ObjectId] , ref: 'User' })
      admin: User[];
    

  2. If you want to add a single item, use $addtoSet without the [] around the findUser._id

    await this.GatewayModel.findOneAndUpdate(
      { admin: userId, channelId: channelId },
      { $addtoSet: { "admin": findUser._id  } }
    )
    

    See how it works on the playground example

    If you want to add an array of MongooseSchema.Types.ObjectId, one option is to use update with pipeline with $setUnion:

    await this.GatewayModel.findOneAndUpdate(
      { admin: userId, channelId: channelId },
      [{$set: {admin: {$setUnion: ["$admin", [findUser._id]]}}}]
    )
    

    See how it works on the playground example

    • I think your schema should be: @Prop({required: true, type: MongooseSchema.Types.ObjectId, ref: 'User' }), since you already have [] around your User
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search