How to Check If Value Exists in a Mongo Collection using Mongoose


Suppose I have a Mongoose collection that follows this simple schema as well as a userId.

How would I check if this userId already exists in the User collection’s _id field?

const userSchema = new Schema({ name: String });
const User = mongoose.model("User", userSchema);

Using findOne()

We could run a findOne query to find a single instance of that userId.

const user = await User.findOne({ _id: userId });
if (user) console.log("User exists");

However, this can be quite slow in a large collection.

Using findOne().lean()

We can increase the speed of this operation by piping two operations at the end: select() and lean().

const user = await User.findOne({ _id: userId }).select("_id").lean();
if (user) console.log("User exists");

select() will allow us to include or exclude certain fields. select("_id") will only return the _id field. select("-_id") will return everything other than _id.

lean() will strip the response data of any Mongoose Document data, which reduces the memory our Node.js process uses (not how much data is sent over the network). As mentioned in the docs:

By default, Mongoose queries return an instance of the Mongoose Document class. Documents are much heavier than vanilla JavaScript objects, because they have a lot of internal state for change tracking. Enabling the lean option tells Mongoose to skip instantiating a full Mongoose document and just give you the POJO (plain old JavaScript objects).

Using exists()

Thankfully, Mongoose heard our prayers and gave us exists(), which runs our second method with additional boolean tricks.

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

const userExists = await User.exists({ _id: userId });
if (userExists) console.log("User exists");