简体   繁体   中英

Nestjs: Property doesn't exists in Mongoose document

I am using Nestjs with Mongoose, and face some challenges with this code:

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()
      })
  }
}

Somehow, my service, within .eachAsync can't see document types.

没有文档类型

The schema file is typical for Nestjs docs:

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

Why such a problem can be, and how to solve it?

I have also tried to make my own special interface. with exactly the same fields as schema and add it to export type KeyDocument = Key & Document<IKey>; but it doesn't work for me.

Seems the solution was trivial, and I start panicking too soon. I just forgot to declare interface type for arg in the eachAsync function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM