2012-05-31 9 views

答えて

23

instanceofオペレータでオブジェクトのプロトタイプを確認して、それがあなたのマングースモデルのインスタンスであることを確認できます。 mongoosejs.comから例のスキーマを使用する:

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

ニース!例えばthis.message =オブジェクトのinstanceofメッセージ?オブジェクト:新しいメッセージ(オブジェクト); – charneykaye

14

を私は使用しています。この

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

これはうまくいきました。上記の答えはJSLintで失敗します – Enkode

+0

'model'は非常に一般的な名前です。 –

0

のObjectIDが移入されたオブジェクトまたは単にオブジェクトIDの場合にチェックした場合には私のためfollwing:

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でもかまいません)に関係なく失敗しません。

関連する問題