【发布时间】:2021-02-13 20:13:05
【问题描述】:
Typescript 在这行抱怨:
user.posts.pull(postId);
我收到此错误:
Property 'pull' does not exist on type 'PostDoc[]'
因为 postId 被接收为req.params.postId 它是字符串类型,所以我将它转换为猫鼬 objectId 但我仍然有同样的错误:
user.posts.pull(mongoose.Types.ObjectId(postId));
pull() 在猫鼬数组中工作。这行代码我是如何在 javacsript 中实现的。我正在将我的项目转换为打字稿。这是用户模型的用户界面和架构。
interface UserDoc extends mongoose.Document {
email: string;
password: string;
posts: PostDoc[];
name: string;
status: string;
}
const userSchema = new Schema({
email: { type: String, required: true },
password: { type: String, required: true },
name: { type: String, required: true },
status: { type: String, default: "I am a new user" },
posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
});
这里发布架构和界面
interface PostDoc extends Document {
title: string;
content: string;
imageUrl: string;
creator: Types.ObjectId;
}
const postSchema = new Schema(
{
title: {
type: String,
required: true,
},
imageUrl: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
creator: {
type: Schema.Types.ObjectId,
ref: "User",
required: true,
},
},
{ timestamps: true }
【问题讨论】:
-
如果您看到错误消息
Property 'pull' does not exist on type 'PostDoc[]',它会告诉您您需要知道的一切 -
@KunalMukherjee 同一行代码在 javascript 中工作。只是切换到打字稿,并不意味着,他们放弃了拉法?
-
请在问题中添加您的帖子架构,它是否扩展
mongoose.Document? -
还可以尝试将 npm 包添加为开发依赖项 - npmjs.com/package/@types/mongoose
-
在接口
PostDoc中Document指的是mongoose.Document对吧,你在上面解构了吗?
标签: javascript node.js typescript mongodb mongoose