【问题标题】:How to mongoose model based on dynamic schema passed as parameter?如何基于作为参数传递的动态模式的猫鼬模型?
【发布时间】: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


【解决方案1】:

这解决了我的问题。

创建一个通用架构和另一个架构

const CommonSchema = new mongoose.Schema({ ... });
const OtherSchema = { ... };
const OtherOtherSchema = { ... };

然后,我宣布了我的基础模型。

const Base = mongoose.model('collection-name', CommonSchema);

接下来,我使用鉴别器基于基本模型创建了我的其他模型

const OtherModel = Base.discriminator("Other", new mongoose.Schema(OtherSchema));
const OtherOtherModel = Base.discriminator("OtherOther", new mongoose.Schema(OtherOtherSchema));

您现在可以在任何作用域函数上使用模型,如果您愿意,可以将其导出。

Other.create({ ... });
Other.findById()

OtherOther.create();
OtherOther.findById();

如果这种方法正确,请告诉我 或者您还有其他建议

谢谢!

【讨论】:

    猜你喜欢
    • 2013-02-04
    • 1970-01-01
    • 2015-03-25
    • 2016-07-03
    • 2022-01-13
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多