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?
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.
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 ).
_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.
findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .
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 }); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With