【发布时间】:2020-05-29 05:56:52
【问题描述】:
我是 mongoose 和 expressjs 的新手
我想根据文档和模型检索一个集合。 我有多个架构继承了一个通用架构。
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, { ... });
然后,我想从 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;
}
};
有可能吗? 提前谢谢!
PS:我已经看到其他帖子,解决方案是使属性成为可选。
【问题讨论】:
-
检查discriminators是否适合您的情况。
-
嗨@SuleymanSah 谢谢。问题解决了。 :)
标签: javascript node.js express mongoose mongoose-schema