Check if ID exists in a collection with mongoose

前端 未结 5 934
無奈伤痛
無奈伤痛 2021-01-31 15:52

For instance, I have a collection User:

var mongoose = require(\'mongoose\');

var UserSchema = new mongoose.Schema({
    email: String,
    googleI         


        
5条回答
  •  抹茶落季
    2021-01-31 16:47

    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.count({_id: userID}, function (err, count){ 
        if(count>0){
            //document exists });
        }
    }); 
    

提交回复
热议问题