I am new on mongoose and for expressjs
I want to retrieve a collection based on the doc and model. I have multiple schema that inherits a common schema.
const extendSchema = (schema: mongoose.Schema<any>, definition: any): Schema<any> => {
return new mongoose.Schema({ ...schema.obj, ...definition, ...{ strict: false }});
};
const CommonSchema = new mongoose.Schema({ ... });
const OtherSchema = extendSchema(CommonSchema, { ... });
const OtherOtherSchema = extendSchema(CommonSchema, { ... });
Then, I want to retrieve the collection from the mongoose
const getCollectionObject = (collection: string, schema: Schema) => {
return collection.model(collection, schema);
};
// get the first collection
export const getOtherCollection = async (name: string, id: string) => {
try {
const model = getCollectionObject(name, OtherSchema);
const document = await model.findById(mongoose.Types.ObjectId(id)).lean();
return document;
} catch (error) {
return error;
}
};
// get the second collection
export const getOtherOtherCollection = async (name: string, id: string) => {
try {
const model = getCollectionObject(name, OtherOtherSchema);
const document = await model.findById(mongoose.Types.ObjectId(id)).lean();
return document;
} catch (error) {
return error;
}
};
Is it possible? Thank you in advance!
PS: I've already saw other posts which the solution is to make the properties optional.
