【问题标题】:Nestjs: Property doesn't exists in Mongoose documentNestjs:猫鼬文档中不存在属性
【发布时间】:2021-07-05 17:02:21
【问题描述】:

我正在将 Nestjs 与 Mongoose 一起使用,并且在使用此代码时面临一些挑战:

import { Injectable } from '@nestjs/common';
import { Key, KeyDocument } from '@app/mongo';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';

@Injectable()
export class KeysService {
  constructor(
    @InjectModel(Key.name) private readonly KeysModel: Model<KeyDocument>
  ) {
    this.test()
  }

  private async test(): Promise<void> {
    await this.KeysModel
      .find()
      .cursor()
      .eachAsync(async (key) => {
        key.token = 'lllsdfsd';
        await key.save()
      })
  }
}

不知何故,我的服务在.eachAsync 内看不到文档类型。

架构文件是 Nestjs 文档的典型文件:

import { Document } from "mongoose";
import { Prop, SchemaFactory } from '@nestjs/mongoose';

export type KeyDocument = Key & Document;

export class Key {
  @Prop()
  _id: string;

  @Prop({ required: true })
  secret: string;

  @Prop()
  token: string;

  @Prop()
  expired_in: number;

  @Prop()
  tags: string[];
}

export const KeysSchema = SchemaFactory.createForClass(Key);

为什么会出现这样的问题,如何解决?

我也尝试过制作自己的特殊界面。具有与架构完全相同的字段并将其添加到export type KeyDocument = Key &amp; Document&lt;IKey&gt;;,但它对我不起作用。

【问题讨论】:

    标签: node.js mongodb typescript mongoose nestjs


    【解决方案1】:

    似乎解决方案很简单,我很快就开始恐慌。我只是忘了在eachAsync 函数中为arg 声明接口类型。

    await this.KeysModel
      .find()
      .cursor()
      .eachAsync(async (key: KeyDocument): Promise<void> => {
         key.token = 'lllsdfsd';
         await key.save()
      })
    

    【讨论】:

      猜你喜欢
      • 2019-12-20
      • 2017-07-05
      • 1970-01-01
      • 2021-01-07
      • 2016-06-17
      • 2021-02-12
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多