在猫鼬模式中扩展接口以添加插件方法
我有一个带有自定义接口的模式模型:
I have a Schema Model with a custom Interface:
interface IPost extends Document {
created: Date;
mensaje: string;
img: string[];
coords: string;
usuario: string;
test: string;
}
我在导出模型时使用这个接口:
I use this interface when exporting model:
export const Post = model<IPost>('Post', postSchema);
我想使用 mongoose-paginate-v2 插件,我已经初始化了:
I would like to use mongoose-paginate-v2 plugin, I initialized:
postSchema.plugin(mongoosePaginate);
如果我在没有 IPost 接口的情况下导出 Post 模型,我可以在我的路由中 .paginate()
,但不能使用我的 IPost 接口.我尝试将方法添加到我的界面,尝试从 mongoose-paginate-v2 类型扩展,但我还没有得到它.
And if I export Post Model without my IPost interface I can .paginate()
in my route, but not with my IPost interface.
I tried adding the method to my interface, trying to extend from mongoose-paginate-v2 types but i haven`t got it.
如何将 mongoose-paginate-v2 中的 .paginate()
方法添加到我的界面?谢谢.
How can I add .paginate()
method from mongoose-paginate-v2 to my interface? Thanks.
我对打字稿也很陌生,因此无法解释整个代码,但这是解决方案.
I too am very new to typescript, thus won't be able to explain the whole code but here's the solution.
/* postModel.ts */
/* postModel.ts */
import { Schema, model, PaginateModel } from 'mongoose';
interface IPost extends Document {
created: Date;
mensaje: string;
img: string[];
coords: string;
usuario: string;
test: string;
}
const postSchema = new Schema({
created: Date.now(),
mensaje: String,
img: [String],
coords: String,
test: String,
})
export default model<IPost, MongooseModel<IPost>>('Post', postSchema);
导入以上文件为:
import postModel from './postModel.ts'
postModel.paginate(filters, options)
您现在可以使用分页功能了.
You'll be able to use paginate function now.
不要忘记添加 mongoose-paginate-v2.我个人喜欢在与数据库建立连接时添加它.这样我就不必在我创建的每个架构中都导入它.
Do not forget to add mongoose-paginate-v2. I personally like to add it while establishing a connection with the database. So that I don't have to import it in every schema that I create.
您可以这样做:
// DEPENDENCIES
import * as mongoose from 'mongoose';
import * as mongoosePaginate from 'mongoose-paginate-v2';
const connection = mongoose.connect(process.env.MONGODB_URI, {
dbName: process.env.DB_NAME,
authSource: 'admin',
user: process.env.DB_USER,
pass: process.env.DB_PASSWORD,
useNewUrlParser: !0,
useUnifiedTopology: !0,
useCreateIndex: !0,
useFindAndModify: !1,
autoIndex: !0,
})
.then(() => {
console.log('Mongoose connected to db');
})
.catch((err: Error) => {
console.log(err.message);
});
mongoose.connection.on('connected', () => {
console.log('Mongodb bridge connected');
});
mongoose.connection.on('error', (err: Error) => {
console.log(`Mongoose connection ERROR: ${err}`);
});
mongoose.connection.on('disconnected', () => {
console.log('Mongoose connection disconnected');
});
process.on('SIGINT', async () => {
await mongoose.connection.close();
process.exit(0);
});
mongoose.plugin(mongoosePaginate);
export default connection;