Check if ID exists in a collection with mongoose

Use count rather than findOne.

This will (under the hood) cause mongoose to use find : http://docs.mongodb.org/manual/reference/method/db.collection.count

findOne() will read + return the document if it exists
On the other hand, find() just returns a cursor (or not) and only reads the data if you iterate over the cursor.
So in our case, we’re not iterating over the cursor, merely counting the results returned.

User.countDocuments({_id: userID}, function (err, count){ 
    if(count>0){
        //document exists });
    }
}); 

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)