【问题标题】:Is there a way to get the model name from a mongoose model instance?有没有办法从猫鼬模型实例中获取模型名称?
【发布时间】:2018-04-12 21:55:06
【问题描述】:

我正在使用猫鼬,我需要从模型实例中找到模型名称。

在我的部分代码中:

 const schema = new mongoose.Schema({
        name: {
            type: String,
            required: true
        },
        phone: {
            type: String,
            required: true
        }
    }

const schema = new mongoose.Schema('MyData', schema);

let instance = new this({
      name: 'Pete',
      phone: '123'
});

这个实例变量在我的代码中传递。稍后我需要找出实例名称,但我不确定是否有办法做到这一点,例如:

let instanceName = getInstanceName(instance); <== Expects 'MyData' to be returned

使用猫鼬可以吗?

【问题讨论】:

  • 你试过用这个instance.constructor.modelName吗?
  • 我试过没有成功,但看到我做错了什么。它可以与instance.constructor.modelName正常工作。谢谢。
  • 我可以将其作为答案发布,以便您接受它作为正确答案吗?谢谢。 :)
  • 当然。你应该。

标签: javascript node.js mongoose


【解决方案1】:

可以使用instance.constructor.modelName访问模型的名称。

【讨论】:

    【解决方案2】:

    我意识到我有一个模型而不是模型的实例,所以我需要使用其他东西。

    如果你有模型,你可以得到如下名称:

    const model = mongoose.model("TestModel", schema);
    const collectionName = model.collection.collectionName;
    

    如果您有模型的特定项目/实例:

    const instance = new model({...});
    const collectionName = instance.constructor.modelName
    

    正如汉娜所说。

    【讨论】:

    • 这是集合名称,不是型号名称。模型名称是model.modelName
    【解决方案3】:

    就我而言,我正在寻找如何从猫鼬模型中获取 discriminator 模型名称,但建议的解决方案不起作用:

    const PerformanceResult = DropDown.discriminator('PerformanceResult', new db.Schema({
        name: { type: String, required: true }
    }))
    export default PerformanceResult
    

    console.log(PerformanceResult.constructor.modelName) // undefined
    console.log(PerformanceResult.collection.collectionName) // DropDown (parent name)
    

    你可以用这个:

    console.log(PerformanceResult.modelName) // PerformanceResult
    

    猫鼬版本:“^5.11.8”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-22
      • 2012-07-31
      • 2013-05-19
      • 1970-01-01
      • 2012-03-29
      • 1970-01-01
      • 2016-10-27
      相关资源
      最近更新 更多