我有一个引用其他文档的方案
import { Document, Schema as MongooseSchema } from 'mongoose';
@Schema()
export class DocumentLinks {
@Prop({ type: [{ type: MongooseSchema.Types.ObjectId, ref: 'Customer' }]})
customers?: [Customer];
...
}
@Schema({ collection: 'documents', toJSON: { virtuals: true, getters: true }, toObject: { virtuals: true, getters: true }})
export class DMSDocument {
@Prop()
links: DocumentLinks;
...
}
在相应的服务中,我只是从通过 api 提供的对象创建新文档:
async create( uploadDocument: UploadDocument ): Promise<DMSDocument | null> {
const createdDocument = new this.documentModel( uploadDocument );
await createdDocument.save();
return createdDocument;
}
现在条目已成功创建,但所有引用都只是存储为字符串,而不是 ObjectID,因此无法引用。
我之前使用过 typegoose,然后由于不兼容而不得不切换回 mongoose。这些引用存储为 ObjectID 就好了。
我不想先验证和转换每个对象,循环遍历数组并手动转换 ObjectId
那么,我在这里错过了什么?
编辑:
我刚刚注意到主架构中的 ID 正在被转换,而不是在子架构中。
答案 0 :(得分:0)
解决方案是在 Prop() 装饰器中使用 raw():
Prop(raw({
customers: { type: [{ type: MongooseSchema.Types.ObjectId, ref: 'Customer' }]}
}))
links: Record<string, any>;
但我仍然希望让事情以更干净的方式工作,例如。使用单独的方案。