猫鼬:检查对象是否是猫鼬对象

猫鼬:检查对象是否是猫鼬对象

问题描述:

有谁知道检查一个对象是否是猫鼬对象的最简单方法是什么?我只是最好检查是否定义了 toObject() 或者是否有更有效的方法.非常感谢

anyone know what the simplest way to check whether an object is a mongoose object? Am I just best checking if toObject() is defined or is there a more efficient way. many thanks

您可以通过 instanceof 运算符检查对象的原型,以确认它是您的猫鼬模型的实例.使用来自 mongoosejs.com 的示例架构:

You can check the object's prototype via the instanceof operator to confirm it's an instance of your mongoose model. Using the example schema from mongoosejs.com:

if (obj instanceof Cat) {
    // yes, it's a mongoose Cat model object
    ...
}