Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose ObjectID's in reference saved as strings

I've got a Scheme referencing other documents

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;

    ...
}

in the corresponding service, I simply create the new document from an object provided via api:

async create( uploadDocument: UploadDocument ): Promise<DMSDocument | null> {
    const createdDocument = new this.documentModel( uploadDocument );
    await createdDocument.save();
    return createdDocument;
}

Now the entry gets successfully created, but all references are simply stored as strings, not ObjectIDs and therefore cannot be referenced.

I've used typegoose before and then had to switch back to mongoose due to incompatibilities. These references were stored as ObjectIDs just fine.

I'd prefer not to validate and convert every object first, loop through arrays and convert ObjectIds manually

So, what am I missing here?

EDIT:

I've just noticed that the IDs in the main Schema are just being converted, just not inside a sub-schema.

like image 443
Janik Avatar asked Jun 16 '26 06:06

Janik


1 Answers

A solution is to use raw() in the Prop() decorator:

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

But I would still prefer to get things working in a more clean way, eg. using a seperate scheme.

like image 92
Janik Avatar answered Jun 22 '26 23:06

Janik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!