54

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?

6 Answers 6

82

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 });
    }
}); 
3
  • 4
    Actually. "Under the hood" this uses the .count() method. Which is a specific method and is generally eh most optimal way to do so. Even though it is true that .count() is actually a "modifier" to a .find() cursor return, it is probably best to actually explain that point rather than leave it in obscurity.
    – Neil Lunn
    Commented Dec 15, 2014 at 11:47
  • 13
    count now triggers a warning: "DeprecationWarning: collection.count is deprecated, and will be removed in a future version. Use collection.countDocuments or collection.estimatedDocumentCount instead".
    – Alex
    Commented Oct 13, 2018 at 23:13
  • 1
    Use countDocuments() instead
    – Mick
    Commented Jul 16, 2021 at 11:43
76

You can now use User.exists() as of September 2019 like so:

const doesUserExit = await User.exists({ _id: userID });

From the docs:

Under the hood, MyModel.exists({ answer: 42 }) is equivalent to MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean().then(doc => !!doc)

1
  • 2
    trying to use this in a pre save hook but getting exists is not a function mongoose - 5.7.13
    – Neil
    Commented Dec 3, 2019 at 20:59
13

The accepted answer is fine for small collections.

A faster way on larger collections is to simply use this:

const result = await User.findOne({ _id: userID }).select("_id").lean();
if (result) {
    // user exists...
}

// or without "async/await":

User.findOne({ _id: userID }).select("_id").lean().then(result => {
    if (result) {
        // user exists...
    }
});

It won't return all fields. I believe they are currently working on a new feature to support what you (and I) want.


In the meantime you could create a plugin, very simple and reusable.

Create an any.js file with this code:

module.exports = function any(schema, options) {
    schema.statics.any = async function (query) {
        const result = await this.findOne(query).select("_id").lean();
        return result ? true : false;
      };
  }

Then in your model you do this:

var mongoose = require('mongoose');
const any = require('./plugins/any'); // I'm assuming you created a "plugins" folder for it

var UserSchema = new mongoose.Schema({
    email: String,
    googleId: String,
    facebookId: String,
    displayName: String,
    active: Boolean
});

UserSchema.plugin(any);
module.exports = mongoose.model('User', UserSchema);

...and use it like this:

const result = await User.any({ _id: userID });
if (result) {
    // user exists...
}

// or without using "async/await":

User.any({ _id: userID }).then(result => {
    if (result) {
        // user exists...
    }
});
4

OR you can simply use exists function, without making any async/await:

myData = {_id: userID};

User.exists(myData,(error, result)=>{
    if (error){
      console.log(error)
    } else {
      console.log("result:", result)  //result is true if myData already exists
    }
  });

You can play with the result now!

0
User.exists({ _id: userID }).then(exists => {
  if (exists) {
    res.redirect('/dashboard')
  } else {
    res.redirect('/login')
  }
})

More info can be found at Mongoose docs.

0

The accepted answer is excellent, but I would really recommend using estimatedDocumentCount() if you are searching existing document by an indexed property (like _id of X).

On the other hand, this should actually work better and is cleaner.

2
  • 1
    p.s. I would love to add this addition to the original answers but I lack StackOverflow "reputation". ✌️
    – svrznjak
    Commented Nov 23, 2022 at 18:06
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Dec 1, 2022 at 6:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.