我在 TypeScript 上有一個 Mongoose,它在沒有定義介面和型別的情況下作業,但是當我決定定義型別時,瘋狂開始了。我看過大量的手冊和主題,發現沒有人有類似的問題。我試圖嚴格按照手冊定義模型,但出現錯誤。這是我的模型檔案:
import mongoose from 'mongoose';
import { nanoid } from 'nanoid';
const GeoSchema = new mongoose.Schema({
type: {
type: String,
default: 'Point',
enum: ['Point'],
},
coordinates: {
type: [Number, Number],
index: '2dsphere',
},
});
interface postInterface extends mongoose.Document {
shortId: string;
createdBy: string;
title: string;
description: string;
tags: string[];
location: {};
images: string[];
contacts: {
email: Boolean;
wa: Boolean;
phone: Boolean;
};
type: 'available' | 'wanted';
is_moderated: Boolean;
}
export const PostSchema = new mongoose.Schema(
{
shortId: {
type: String,
index: true,
default: () => nanoid(),
},
createdBy: {
type: String,
index: true,
},
title: String,
description: String,
tags: [String],
location: GeoSchema,
images: [String],
contacts: {
email: Boolean,
wa: Boolean,
phone: Boolean,
},
type: { type: String, enum: ['available', 'wanted'] },
is_moderated: Boolean,
},
{ timestamps: true }
);
export const Post = mongoose.model<postInterface>('Post', PostSchema);
當我將它匯入另一個檔案時,就行了
return Post.create(post)
linter 給了我錯誤:
Type 'postInterface & { _id: any; }' is missing the following properties from type 'Schema<any, Model<any, any, any, any>, {}, {}>': add, childSchemas, clearIndexes, clone, and 37 more.ts(2740)
我用谷歌搜索了打字稿模型定義的例子,看起來對別人有用的東西對我不起作用。
我究竟做錯了什么?
更新
伙計,這太明顯了!我匯入模型的檔案如下所示:
import { Post, PostSchema } from '../models/post.model';
export class PostService {
async createPost(post: any): Promise<typeof PostSchema | null> {
return Post.create(post);
}
async getPostById(shortId: string): Promise<typeof PostSchema | null> {
return Post.findOne({ shortId });
}
}
所以事情在Promise<typeof PostSchema | null>. 當我將代碼更改為此時,錯誤消失了:
import { Post, postInterface } from '../models/post.model';
export class PostService {
async createPost(post: any): Promise<postInterface | null> {
return Post.create(post);
}
async getPostById(shortId: string): Promise<postInterface | null> {
return Post.findOne({ shortId });
}
}
感謝@lpizzinidev 將我推向正確的方向!
uj5u.com熱心網友回復:
伙計,這太明顯了!我匯入模型的檔案如下所示:
import { Post, PostSchema } from '../models/post.model';
export class PostService {
async createPost(post: any): Promise<typeof PostSchema | null> {
return Post.create(post);
}
async getPostById(shortId: string): Promise<typeof PostSchema | null> {
return Post.findOne({ shortId });
}
}
所以事情在Promise<typeof PostSchema | null>. 當我將代碼更改為此時,錯誤消失了:
import { Post, postInterface } from '../models/post.model';
export class PostService {
async createPost(post: any): Promise<postInterface | null> {
return Post.create(post);
}
async getPostById(shortId: string): Promise<postInterface | null> {
return Post.findOne({ shortId });
}
}
感謝@lpizzinidev 將我推向正確的方向!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487249.html
標籤:javascript 打字稿 mongodb 猫鼬
