Home > Back-end >  Expected a valid update modifier using $addToSet MongoDb Nestjs
Expected a valid update modifier using $addToSet MongoDb Nestjs

Time:01-13

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

CodePudding user response:

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

CodePudding user response:

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[];
  • Related