簡體   English   中英

Nest.js:在 mongoose 中的 model 上的 .find 始終返回空數組

[英]Nest.js: .find on model in mongoose always returns empty array

正如標題所描述的,即使數據正確,它也總是返回一個空數組:

數據庫.service.ts

async updateReply(id: string, attributes: Partial<ReplyDto>) {
    console.log('Path request update reply with id: ' + id + ' and body:', attributes);
    const reply = await this.replyModel.find({ _id: id });

    // This was the previous way of fetching and update the object:
    //
    // const reply = await this.replyModel.findOneAndUpdate(
    //     { _id: new mongoose.Types.ObjectId(id) },
    //     { $set: attributes },
    //     { new: true }
    // );
    
    console.log('Reply updated: ', reply);
    return reply;
}

回復.service.ts

async updateReply(id: string, body: UpdateReplyDto) {
    console.log('Path request update reply with id: ' + id + ' and body:', body);
    return await this.databaseService.updateReply(id, body);
}

回復.controller.ts

@Patch('/update/:id')
updateReplyById(@Param('id') id: string, @Body() body: UpdateReplyDto) {
    console.log('Path request update reply with id: ' + id + ' and body:', body);
    return this.repliesService.updateReply(id, body);
}

更新回復.dto.ts

import { IsArray, IsNumber, IsOptional, IsString } from "class-validator";

export class UpdateReplyDto {
    @IsString()
    @IsOptional()
    languageCode: string;

    @IsArray()
    @IsNumber({ allowNaN: false}, { each: true })
    @IsOptional()
    stars: string[];

    @IsArray()
    @IsOptional()
    keywords: string[];

    @IsArray()
    @IsOptional()
    comments: string[];
}

回復.dto.ts

import { Expose, Transform, Type } from "class-transformer";
import mongoose, { Types } from "mongoose";

export class ReplyDto {
    @Expose({ name: '_id' })
    // makes sure that when deserializing from a Mongoose Object, ObjectId is serialized into a string
    @Transform((value: any) => {
      if ('value' in value) {
        return value.value instanceof mongoose.Types.ObjectId ? value.value.toHexString() : value.value.toString();
      }
  
      return 'unknown value';
    })
    public id: string;

    @Expose()
    languageCode: string;

    @Expose()
    stars: string[];

    @Expose()
    keywords: string[];

    @Expose()
    comments: string[];

    @Expose()
    createdAt: Date;

    @Expose()
    updatedAt: Date;
}

日志:

來自 Controller:路徑請求更新回復,ID:62f6df243eb6410001621b90 和正文:{語言代碼:'en',關鍵字:['hey','you','friend','hello']}

來自服務:路徑請求更新回復,ID:62f6df243eb6410001621b90 和正文:{語言代碼:'en',關鍵字:['hey','you','friend','hello']}

來自數據庫服務:路徑請求更新回復,ID:62f6df243eb6410001621b90 和正文:{語言代碼:'en',關鍵字:['hey','you','friend','hello']}

.find 回復:回復更新:[]

答案在於代碼的注釋部分:

const reply = await this.replyModel.find({ _id: id });

// This was the previous way of fetching and update the object:
//
// const reply = await this.replyModel.findOneAndUpdate(
//     { _id: new mongoose.Types.ObjectId(id) },
//     { $set: attributes },
//     { new: true }
// );

您需要將id轉換為ObjectId ,試試這個:

const reply = await this.replyModel.find({ _id: new mongoose.Types.ObjectId(id) });

我找到了答案,出現問題是因為我想通過這樣做將_id鍵更改為id

@Expose({ name: '_id' })
// makes sure that when deserializing from a Mongoose Object, ObjectId is serialized into a string
@Transform((value: any) => {
  if ('value' in value) {
    return value.value instanceof mongoose.Types.ObjectId ? value.value.toHexString() : value.value.toString();
  }

  return 'unknown value';
})
public id: string;

但實際上正確的方法只是@Expose() id: string; .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM