如何将 MongooseArray.prototype.pull() 与打字稿一起使用?

Yil*_*maz 4 javascript mongoose mongodb node.js typescript

Typescript 在这一行抱怨:

user.posts.pull(postId);
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

     Property 'pull' does not exist on type 'PostDoc[]'
Run Code Online (Sandbox Code Playgroud)

由于 postId 被接收为req.params.postId字符串类型,所以我将其转换为 mongoose objectId 但我仍然有相同的错误:

  user.posts.pull(mongoose.Types.ObjectId(postId));
Run Code Online (Sandbox Code Playgroud)

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" }],
});
Run Code Online (Sandbox Code Playgroud)

这里发布架构和接口

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 }
Run Code Online (Sandbox Code Playgroud)

Sou*_*non 8

我在正确输入子文档时遇到了类似的问题。我向您建议以下解决方案,以便保持 DTO 接口和模型接口分离并强类型化。这同样适用于您的PostDoc.

用户文档DTO

interface UserDoc {
  email: string;
  password: string;
  posts: PostDoc[];
  name: string;
  status: string;
}
Run Code Online (Sandbox Code Playgroud)

用户文档模型

export type UserDocModel = UserDoc & mongoose.Document & PostDocModel & Omit<UserDoc , 'posts'>

interface PostDocModel {
  posts: mongoose.Types.Array<PostModel>;
};
Run Code Online (Sandbox Code Playgroud)

我们将mongoose 数组posts: PostDoc[]属性替换为Omit 保持属性同步。灵感来自/sf/answers/2566339331/PostModel

这样我们就可以访问每个 mongoose 数组方法,例如pullpopshift等(https://mongoosejs.com/docs/api.html#Array

const user = await this.userdocModel.findById(userId).exec();
user.posts.pull(postId);
Run Code Online (Sandbox Code Playgroud)

导出模型

const User = mongoose.model<UserDocModel>('User', userSchema);
export default User;
Run Code Online (Sandbox Code Playgroud)