我有一个带有自定义界面的模式模型:
interface IPost extends Document {
created: Date;
mensaje: string;
img: string[];
coords: string;
usuario: string;
test: string;
}
我在导出模型时使用此界面:
export const Post = model<IPost>('Post', postSchema);
我想使用mongoose-paginate-v2插件,我已初始化:
postSchema.plugin(mongoosePaginate);
如果我在没有 IPost接口的情况下导出 Post Model ,我可以在路由中.paginate()
,但不能使用IPost接口。
我尝试将方法添加到我的界面中,尝试从mongoose-paginate-v2类型扩展,但是我还没有。
如何从mongoose-paginate-v2中向我的界面添加.paginate()
方法?谢谢。
答案 0 :(得分:0)
您可以自己扩展
interface IPpaginator {
paginate(): void;
}
interface IPost extends Document, IPpaginator {
created: Date;
mensaje: string;
img: string[];
coords: string;
usuario: string;
test: string;
}
更新
// import dependencies
import { Document, Schema, Model, model} from "mongoose";
//export like a boss
export const Post: Model<IPost> = model<IPost>('Post', postSchema);
答案 1 :(得分:0)
我对打字稿也很陌生,因此无法解释整个代码,但这是解决方案。
/* 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)
您现在可以使用分页功能了。
编辑: 不要忘记添加 mongoose-paginate-v2。 我个人喜欢在与数据库建立连接时添加它。这样我就不必在我创建的每个架构中都导入它。
您可以这样做:
// 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;