我喜欢虚拟 Mongoose ,但我不能让它在打字稿工作。
我使用mongoose的InferSchemaType来创建接口,如mongoose documentation中的“另一种方法:“中所述
TSC不会将它们识别为接口中的字段。
我尝试了两种建议的方式(见下面的代码)。
import {connect, InferSchemaType, Schema, model} from 'mongoose';
const url = 'mongodb://admin:admin@0.0.0.0:27017/';
export const DBS_Actor = new Schema(
{
firstName: String,
lastName: String,
},
{
virtuals: {
fullName: {
get() {
return this.firstName + ' ' + this.lastName;
},
},
},
}
);
DBS_Actor.virtual('tagname').get(function () {
return 'Secrete Agent 007';
});
export type IActor = InferSchemaType<typeof DBS_Actor>;
export const Actor = model<IActor>('User', DBS_Actor);
run().catch(err => console.log(err));
async function run() {
await connect(url);
const actor = new Actor({
firstName: 'jojo',
lastName: 'kiki',
});
await actor.save();
console.log(actor.toJSON()); // {firstName: 'jojo', lastName: 'kiki', _id: new ObjectId("62e52b18d41b2bd4d2bd08d8"), __v: 0 }
console.log(actor.firstName); // jojo
// console.log(actor.fullname); //TSC error TS2339: Property 'fullname' does not exist on typ
// console.log(actor.tagname); //TSC error TS2339: Property 'tagname' does not exist on type...
}
1条答案
按热度按时间huwehgph1#
如果要在类型上使用其他字段,可以扩展类型: