Abbas
Abbas

Reputation: 1255

How to check if a document exists without retrieving it: Mongoose

I am using Mongoose to connect to MongoDB and perform CRUD operations on it. One of my collections has a lot of data in its individual documents (records). At a point in my code, I want to check if a document with particular id field exists already in the collection, and if it does, then I can show a proper error to the user.

Currently, I am using the findOne() method available in the Mongoose library. The problem with this method (or any other find prefixed methods) is that it retrieves the data, which takes a bit time if there is a crazy bunch of data stored.

I am looking for a way to get some kind of boolean as a result indicating if the document exists or not, without actually getting the whole document itself.

Upvotes: 0

Views: 944

Answers (2)

Sachin Shah
Sachin Shah

Reputation: 4533

Pass id in findOne()

Make a one common function.

const objectID = require('mongodb').ObjectID
getMongoObjectId(id) {   
    return new objectID(id)
}

Now just call function

findOne({_id:common.getMongoObjectId('ID value hear')})

It will same as where condition in mysql.

Upvotes: 0

Andrew1996
Andrew1996

Reputation: 436

Alternatively you could use countDocuments() to check the number of documents in the query? This will just count the number rather than returning it.

Upvotes: 2

Related Questions