'model' 属性 在 'IUserDocument' 类型中不存在

The 'model' property does not exist in the 'IUserDocument' type

我正在尝试创建自己的界面并从 Mongoose 扩展 Document,所以我做到了:

users.types.ts

import { Document, Model } from 'mongoose'

export interface IUser {
    chatId: Number,
    username: String,
    name?: String,
    firstName?: String,
    lastName?: String,
    age?: Number,
    sex?: String,
    partner?: String,
    updatedAt?: Date
}

export interface IUserDocument extends IUser, Document {
    setLastUpdated: (this: IUserDocument) => Promise<void>
}

export interface IUserModel extends Model<IUserDocument> {
    findOneOrCreate: ({
        chatId,
        username,
    }: {
        chatId: Number
        username: String
        age: number
    }) => Promise<IUserDocument>
}

然后:

users.methods.ts

import { Document } from "mongoose"
import { IUserDocument } from "./users.types"

export async function setLastUpdated(this: IUserDocument): Promise<void> {
    const now = new Date()
    if (!this.updatedAt || this.updatedAt < now) {
        this.updatedAt = now
        await this.save()
    }
}

export async function setUsername(this: IUserDocument): Promise<Document[]> {
    return this.model("user").find({ username: this.username })
}

现在我得到以下错误:

The 'model' property does not exist in the 'IUserDocument' type. Did you mean '$model'?

在以下行中:

return this.model("user").find({ username: this.username })

此外,我也遇到了 this 的问题,事实上,如果我尝试以这种方式调用模型:

users.statics.ts

import { IUserDocument } from './users.types'

export async function findOneOrCreate({
    chatId,
    username
}: {
    chatId: Number
    username: String
}) {

    const record = await this.findOne({ chatId, username })

    if (record) {
        return record
    } else {
        return this.create(chatId, username)
    }
}

我收到这个错误:

'this' implicitly contains the type 'any' because it does not include a type annotation.

有人可以帮忙吗?

我不熟悉猫鼬,但根据文档:

model() 在 moongose 实例上调用。大概是这样的

import mongoose, { Document } from "mongoose"
[...]
return mongoose.model("user").find({ username: this.username })

findOne() and create() 在模型上调用。所以你可能应该输入一个 IUserModelfindOneOrCreate.

this 在 Javascript 中有特殊含义,可能不是您想要使用的。