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
How I modified and it works now.
Schema:
If you want to add a single item, use
$addtoSet
without the[]
around thefindUser._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
:See how it works on the playground example
@Prop({required: true, type: MongooseSchema.Types.ObjectId, ref: 'User' })
, since you already have[]
around yourUser