Skip to content

[Mongoose] Cream does not work with mongoose documents

when returing a document from a mongoose query the reflection metadata is not inserted. This can be fixed by changing the prototype of mongoose functions. --- Edit ---

IMPORTANT SUGGESTION

It is also suggested to use mongoose-autopopulate along this plugin.

This is the code that implements the reloading of the class reflection data when objects are returned from the database

import { Constructable } from '@creamapi/cream';
import { Schema } from 'mongoose';

export function loadReflectionsOnSave<T extends Object>(
	classType: Constructable<T>
) {
	let fun = (docs: any) => {
		if (!Array.isArray(docs)) {
			docs = [docs];
		}

		for (let doc of docs) {
			let metaKeys = Reflect.getMetadataKeys(classType.prototype);
			for (let metaKey of metaKeys) {
				Reflect.defineMetadata(
					metaKey,
					Reflect.getMetadata(metaKey, classType.prototype),
					doc
				);
			}

			for (let docKey in doc) {
				let fieldMetaKeys = Reflect.getOwnMetadataKeys(
					classType.prototype,
					docKey
				);

				for (let fieldMetaKey of fieldMetaKeys) {
					Reflect.defineMetadata(
						fieldMetaKey,
						Reflect.getOwnMetadata(
							fieldMetaKey,
							classType.prototype,
							docKey
						),
						doc,
						docKey
					);
				}
			}
		}
	};

	return function (schema: Schema, options: any) {
		schema.post(/find.*/, fun);
		schema.post('save', fun);
		schema.post(/update.*/, fun);
	};
}
Edited by Raul Radu