2012-05-31 57 views

回答

23

您可以通过instanceof运算符检查对象的原型,以确认它是猫鼬模型的一个实例。从mongoosejs.com使用示例模式:

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

不错!例如this.message =对象instanceof消息? object:new Message(object); – charneykaye

14

我使用这个

if (object.constructor.name === 'model') { 
    // object is mongoose object 
} 
+0

这一个工作,上面的答案在JSLint – Enkode

+0

失败'模型'是一个非常通用的名称。 –

0

在检查的情况下,对我来说,follwing当一个对象ID是一个人口稠密的对象或只是一个对象ID:

if (object._id.constructor.name === 'ObjectID') { 
    // Not a populated object, only its ID 
} 
0

要检查是否obj是猫鼬的对象,使用此片段:

const _ = require('lodash'); 
const mongoose = require('mongoose'); 

function checkIfMongooseObject(obj) { 
    return _.get(charger, 'constructor.base') instanceof mongoose.Mongoose; 
} 

与其他提供的解决方案相反,这是安全的 - 它永远不会失败,无论类型为obj(甚至是String或Int)。