有没有办法从mongoose模型实例中获取模型名称?

时间:2017-10-31 16:38:33

标签: javascript node.js mongoose

我正在使用mongoose,我需要从模型实例中找到一个模型名称。

在我的代码的一部分中:

 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

使用猫鼬可以吗?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

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

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

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

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

如汉娜(Hannah)所述。

相关问题