Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if ID exists in a collection with mongoose

For instance, I have a collection User:

var mongoose = require('mongoose');  var UserSchema = new mongoose.Schema({     email: String,     googleId: String,     facebookId: String,     displayName: String,     active: Boolean });  module.exports = mongoose.model('User', UserSchema); 

And then I have an ID:

var userID = "some-user-id" 

What is the right way to just check if this id exists in the User collection. I don't need it to read the file or return it, I just need the true or false value.

Here is one way to achieve it:

User.findOne({      _id: userID }, function (err, existingUser) { 

But is there faster and more efficient way?

like image 255
Michael Avatar asked Dec 15 '14 11:12

Michael


People also ask

How to check if document exists in Mongoose?

What is exists() 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.

What is the difference between id and _ID in Mongoose?

So, basically, the id getter returns a string representation of the document's _id (which is added to all MongoDB documents by default and have a default type of ObjectId ). Regarding what's better for referencing, that depends entirely on the context (i.e., do you want an ObjectId or a string ).

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.

What does find by id return Mongoose?

findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .


1 Answers

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 });     } });  
like image 91
Alex Avatar answered Sep 25 '22 21:09

Alex