I'm trying to create my own interface and extend the Document
from Mongoose
, so I did:
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>
}
and then:
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 })
}
Now I get the following error:
The 'model' property does not exist in the 'IUserDocument' type. Did you mean '$model'?
on the following line:
return this.model("user").find({ username: this.username })
Also, I'm facing problem with this
too, infact if I try to call the model in this way:
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)
}
}
I get this error:
'this' implicitly contains the type 'any' because it does not include a type annotation.
Could someone help?
CodePudding user response:
I'm not familiar with mongoose, but according to the documentation:
model()
is called on the moongose instance. Probably something like this
import mongoose, { Document } from "mongoose"
[...]
return mongoose.model("user").find({ username: this.username })
findOne()
and create()
is called on the model. So you probably should input an IUserModel
into findOneOrCreate
.
this
has a special meaning in Javascript and is probably not what you want to use.