Node.js 如何将mongoosarray.prototype.pull()与typescript一起使用?

Node.js 如何将mongoosarray.prototype.pull()与typescript一起使用?,node.js,typescript,mongoose,Node.js,Typescript,Mongoose,Typescript正在这一行抱怨: user.posts.pull(postId); 我得到这个错误: Property 'pull' does not exist on type 'PostDoc[]' 由于postId作为req.params.postId接收,因此它是字符串类型,因此我将其转换为mongoose objectId,但仍然存在相同的错误: user.posts.pull(mongoose.Types.ObjectId(postId)); pull()在m

Typescript正在这一行抱怨:

user.posts.pull(postId);
我得到这个错误:

     Property 'pull' does not exist on type 'PostDoc[]'
由于postId作为
req.params.postId
接收,因此它是字符串类型,因此我将其转换为mongoose objectId,但仍然存在相同的错误:

  user.posts.pull(mongoose.Types.ObjectId(postId));
pull()在mongoose数组中工作。这行代码是我如何在JavaCScript中实现的。我正在将我的项目转换为typescript。这是用户模型的用户界面和模式

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 }

为了正确地键入子文档,我遇到了类似的问题。我建议您使用以下解决方案,以保持DTO接口和模型接口分离并保持强类型。这同样适用于你的
博士后

用户文档DTO 用户文档模型 导出模型
const User=mongoose.model('User',userSchema);
导出默认用户;

如果您看到错误消息,
类型“PostDoc[]”上不存在属性“pull”
,它会告诉您需要执行的所有操作know@KunalMukherjee同一行代码在javascript中工作。只是切换到typescript,并不意味着他们放弃了pull方法?请在问题中添加您的post模式,它是否扩展了
mongoose.Document
?还可以尝试添加npm包作为开发依赖项-在接口
PostDoc
Document
指的是
mongoose.Document
对,你在上面分解过吗?这是非常有用的信息。我学到了很多。首先,你是如何初始化这个.userdocModel的。我像这样使用“await UserDocModel.findById(req.userId)”,但不起作用我只是意识到UserDocModel只是一个类型,所以不能用它代替User@Yilmaz在我的例子中,我使用NestJS(docs.NestJS.com/technologies/mongodb)(Node.js框架)注入和初始化模型。然而,我认为您应该能够导出模型并像这样使用它:const User=mongoose.model('User',userSchema);出口用户;
interface UserDoc {
  email: string;
  password: string;
  posts: PostDoc[];
  name: string;
  status: string;
}
export type UserDocModel = UserDoc & mongoose.Document & PostDocModel & Omit<UserDoc , 'posts'>

interface PostDocModel {
  posts: mongoose.Types.Array<PostModel>;
};
const user = await this.userdocModel.findById(userId).exec();
user.posts.pull(postId);
const User = mongoose.model<UserDocModel>('User', userSchema);
export default User;