首先說明:我使用的是@nestjs/mongoose,我不知道問題是因為@nestjs/mongoose 還是純mongodb。
我想使用@nestjs/mongoose 訪問嵌入檔案的_id。然而 mongoose 檔案物件不包含嵌入檔案的 _id。
在我的背景關系中,Category 嵌入在 Topic 中。我想達到類別的_id。
“主題”定義:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { CategorySchema, Category } from './category.schema';
export type TopicDocument = Topic & Document;
@Schema()
export class Topic {
@Prop()
name: string;
@Prop({ type: [CategorySchema] })
categories: Category[];
}
export const TopicSchema = SchemaFactory.createForClass(Topic);
“類別”定義:
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { Activity, ActivitySchema } from './activity.schema';
export type CategoryDocument = Category & Document;
@Schema()
export class Category {
@Prop({ _id: true })
_id: number;
@Prop()
name: string;
@Prop()
image: string;
@Prop({ type: [ActivitySchema] })
activities: Activity[];
}
export const CategorySchema = SchemaFactory.createForClass(Category);
當我運行這個:
const topics: Topic[] = await this.topicModel.find({ _id: topicId }).exec();
這是預期的結果:
然而這是結果:(不包含嵌入檔案的_id)
有什么解決辦法嗎?
附注:我可以使用lean() 而不是exec() 來獲取嵌入檔案的_id,lean() 回傳JS 物件。但是,由于它的 JS 物件,它不會讓我使用 save()
uj5u.com熱心網友回復:
解決了!
看起來我必須為 id 擴展 Document。
添加 id 作為 Prop 是一個錯誤的覆寫選項。
@Schema()
export class Category extends Document {
@Prop()
name: string;
@Prop()
image: string;
@Prop({ type: [ActivitySchema] })
activities: Activity[];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470263.html
上一篇:如何優化MongoDB查詢?