我正在尝试在使用多个连接 (following the docs) 时创建模型,但出现以下错误:
TS2345: Argument of type 'Schema<Document<any>, Model<Document<any>>>' is not assignable to parameter of
type 'Schema<UserInterface, UserModelInterface>'.
Types of property 'methods' are incompatible.
... (a bunch of 'is not assignable - is missing the following properties' errors follow) ...
我的代码如下:
database.ts
import mongoose from "mongoose";
// const mongo = mongoose.connection(process.env.DB_URI!, {
const mongo = mongoose.createConnection(process.env.DB_URI!, {
useUnifiedTopology: true,
useNewUrlParser: true,
useFindAndModify: false,
useCreateIndex: true
})
export default mongo
UserModel.ts
import mongoose, {Model} from 'mongoose';
import bcrypt from 'bcrypt'
import database from "../database";
interface UserDocumentInterface extends mongoose.Document {
firstname: string
lastname: string
...
}
interface UserInterface extends UserDocumentInterface {
// Instance methods
hashPassword(password: string): Promise<string>
...
}
export interface UserModelInterface extends Model<UserInterface> {
// Static methods
// Currently empty
}
const UserSchema = new mongoose.Schema({
firstname: {
type: String,
required: true,
trim: true
},
lastname: {
type: String,
required: true,
index: true,
trim: true,
},
...
})
// Methods definitions
UserSchema.methods.hashPassword = async function(password) {
return await bcrypt.hash(password, 10);
}
...
// const User: UserModelInterface = mongoose.model<UserInterface, UserModelInterface>('User', UserSchema)
const User = database.model<UserInterface, UserModelInterface>('User', UserSchema)
export default User
错误出现在 UserSchema
中的 const User = database.model<UserInterface, UserModelInterface>('User', UserSchema)
我不明白为什么这条线没有问题
const User: UserModelInterface = mongoose.model<UserInterface, UserModelInterface>('User', UserSchema)
但是这个会报错
const User = database.model<UserInterface, UserModelInterface>('User', UserSchema)
当唯一改变的是连接类型时,mongoose.createConnection()
而不是 mongoose 默认连接