【问题标题】:How can I use MongooseArray.prototype.pull() with typescript?如何将 MongooseArray.prototype.pull() 与打字稿一起使用?
【发布时间】:2021-02-13 20:13:05
【问题描述】:

Typescript 在这行抱怨:

user.posts.pull(postId);

我收到此错误:

     Property 'pull' does not exist on type 'PostDoc[]'

因为 postId 被接收为req.params.postId 它是字符串类型,所以我将它转换为猫鼬 ob​​jectId 但我仍然有同样的错误:

  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
  • 在接口PostDocDocument指的是mongoose.Document对吧,你在上面解构了吗?

标签: javascript node.js typescript mongodb mongoose


【解决方案1】:

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

UserDoc DTO

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>;
};

对于PostModelmongoose 数组,我们将posts: PostDoc[] 属性替换为Omit,保持属性同步。灵感来自https://stackoverflow.com/a/36661990

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

const user = await this.userdocModel.findById(userId).exec();
user.posts.pull(postId);

导出模型

const User = mongoose.model<UserDocModel>('User', userSchema);
export default User;

【讨论】:

  • 这是非常有用的信息。我学到了很多。一件事,你是如何初始化this.userdocModel的。我这样用过“await UserDocModel.findById(req.userId)”但没用
  • 我才意识到 UserDocModel 只是类型,所以不能用来代替 User
  • @Yilmaz 在我的情况下,我使用 NestJS (docs.nestjs.com/techniques/mongodb)(一个 Node.js 框架)来注入和初始化模型。但是我认为您应该能够导出模型并像这样使用它: const User = mongoose.model('User', userSchema);导出用户;
猜你喜欢
  • 2017-08-15
  • 2017-12-25
  • 2019-04-18
  • 2021-08-21
  • 1970-01-01
  • 2022-11-06
  • 2021-08-14
  • 1970-01-01
  • 2021-09-28
相关资源
最近更新 更多