nestJs mongoose ошибка при использовании методов
Здраствуйте дорогие форумчане!
Недавно столкнулся с некой ошибкой при использовании NestJs+mongoDb
Вот моя модель юзера:
import * as mongoose from 'mongoose';
import { Upload } from '../../upload/schemas/upload.schema';
import { Language } from '../enums/language.enum';
import { Roles } from '../enums/role.enum';
export type UserDocument = User & mongoose.Document;
@Schema({ timestamps: true, id: true })
export class User {
@Prop({
index: true,
required: true,
unique: true,
})
email: string;
@Prop({ required: true })
password: string;
@Prop({
unique: true,
index: true,
required: true,
})
nickname: string;
@Prop({
ref: 'Upload',
index: true,
required: false,
type: mongoose.Schema.Types.ObjectId,
})
avatarImage: Upload;
@Prop({
enum: Object.keys(Language),
trim: true,
default: 'en',
})
lang: string;
@Prop({
type: [
{
ref: 'User',
type: mongoose.Schema.Types.ObjectId,
index: true,
},
],
default: [],
})
followers: this[];
@Prop({
type: [
{
ref: 'User',
type: mongoose.Schema.Types.ObjectId,
index: true,
},
],
default: [],
})
following: this[];
@Prop({
type: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
index: true,
},
],
default: [],
index: true,
select: false,
})
blockedUsers: this[];
@Prop({
type: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
index: true,
},
],
default: [],
index: true,
select: false,
})
blockedByUsers: this[];
@Prop({
trim: true,
select: false,
default: 'user',
enum: Object.keys(Roles),
})
role: string;
@Prop({ select: false, default: false })
del: boolean;
@Prop({ default: null, select: false })
deletedAt: Date;
}
export const UserSchema = SchemaFactory.createForClass(User);
Вот так я подключаю ету схему к модулю:
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { LoggerModule } from './../logger/logger.module';
import { UserSchema, User } from './schemas/user.schema';
import { UserController } from './user.controller';
import { UserService } from './user.service';
@Module({
imports: [
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
LoggerModule,
],
controllers: [UserController],
providers: [UserService],
exports: [UserService],
})
export class UserModule {}
И вот так у сервис:
@Injectable()
export class UserService {
constructor(
@InjectModel(User.name) private userModel: Model<UserDocument>,
private readonly logger: LoggerService,
) {
this.logger.setContext('users');
}
}
Дальше припустим мне нужно постучаться в blockedUsers чтобы узнать не заблокирован ли юзер. Делаю я ето таким способом:
async follow({ _id }: IUser, user: IUser): Promise<void> {
try {
await this.userModel.findOneAndUpdate(
{
_id,
del: false,
blockedByUsers: {
$nin: [user._id],
},
blockedUsers: {
$nin: [user._id],
},
},
{
$addToSet: {
followers: [user._id],
},
},
);
} catch (err) {
const error = 'Failed to update user';
this.logger.error(error, err);
throw new InternalServerErrorException(null, error);
}
try {
await this.userModel.findOneAndUpdate(
{
_id: user._id,
del: false,
blockedByUsers: {
$nin: [_id],
},
blockedUsers: {
$nin: [_id],
},
},
{
$addToSet: {
following: [_id],
},
},
);
} catch (err) {
const error = 'Failed to update user';
this.logger.error(error, err);
throw new InternalServerErrorException(null, error);
}
this.logger.log(`user ${user._id} followed ${_id}`);
}
И вот на етом етапе у меня появляется ошибка
Type '{ $nin: User[]; }' is not assignable to type 'Condition<UserDocument[]>'. Types of property '$nin' are incompatible. Type 'User[]' is not assignable to type '(UserDocument | UserDocument[])[]'.ts(2322)
Вот мой интерфейс IUser:
import { Document } from 'mongoose';
import { Upload } from 'src/upload/schemas/upload.schema';
import { User } from 'src/user/schemas/user.schema';
export interface IUser extends Document {
readonly _id?: User;
readonly email: string;
readonly password: string;
readonly nickname: string;
readonly avatarImage: Upload;
readonly lang: string;
readonly followers: User[];
readonly following: User[];
readonly blockedUsers: User[];
readonly blockedByUsers: User[];
readonly role: string;
readonly del: boolean;
readonly deletedAt: Date;
readonly updatedAt?: Date;
readonly createdAt?: Date;
}
Есть подозрения что данная ошибка возникла из-за использования this.
Помогите чем можете пожалуйста. Буду очень благодарен! ссылка на git репозиторий: https://gitlab.com/TopMemeDay/api/-/tree/task-1