【问题标题】:Mongoose ObjectID's in reference saved as strings参考中的 Mongoose ObjectID 保存为字符串
【发布时间】:2021-05-06 14:46:13
【问题描述】:

我有一个引用其他文档的方案

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 就好了。

我不希望首先验证和转换每个对象,循环遍历数组并手动转换 ObjectIds

那么,我在这里错过了什么?

编辑:

我刚刚注意到主架构中的 ID 只是被转换,而不是在子架构中。

【问题讨论】:

    标签: mongoose nestjs


    【解决方案1】:

    解决方案是在 Prop() 装饰器中使用 raw()

    Prop(raw({
        customers: { type: [{ type: MongooseSchema.Types.ObjectId, ref: 'Customer' }]}
    }))
    links: Record<string, any>;
    

    但我仍然希望以更干净的方式工作,例如。使用单独的方案。

    【讨论】:

      猜你喜欢
      • 2015-12-13
      • 2013-05-18
      • 2019-06-23
      • 2020-12-03
      • 2016-06-12
      • 1970-01-01
      • 2015-01-17
      • 2015-06-08
      • 1970-01-01
      相关资源
      最近更新 更多