简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM