Janik
Janik

Reputation: 121

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.

Upvotes: 3

Views: 511

Answers (1)

Janik
Janik

Reputation: 121

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.

Upvotes: 1

Related Questions