Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: check if object is mongoose object

Tags:

mongoose

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

like image 225
Chin Avatar asked May 31 '12 03:05

Chin


People also ask

How to check if object is mongoose object?

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 ... }

Is exist in mongoose?

exists is a Mongoose method or function that is used to check if at least one document exists that matches a specified filter. If there is a match, true is returned. Otherwise, false is returned.

Does Mongoose auto generate ID?

_id field is auto generated by Mongoose and gets attached to the Model, and at the time of saving/inserting the document into MongoDB, MongoDB will use that unique _id field which was generated by Mongoose.

Which module is internally used by mongoose?

Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node. js server. Advantages of Mongoose module: Collection validation of the MongoDB database can be done easily.


2 Answers

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     ... } 
like image 189
JohnnyHK Avatar answered Sep 20 '22 17:09

JohnnyHK


I'm using this

if (object.constructor.name === 'model') {   // object is mongoose object } 
like image 38
mishimay Avatar answered Sep 18 '22 17:09

mishimay