77

I am writing a NodeJS server with ExpressJS, PassportJS, MongoDB and MongooseJS. I just managed to get PassportJS to use user data obtained via Mongoose to authenticate.

But to make it work, I had to use a "findById" function like below.

var UserModel = db.model('User',UserSchema);

UserModel.findById(id, function (err, user) { < SOME CODE > } );

UserModel is a Mongoose model. I declare the schema, UserSchema earlier. So I suppose UserModel.findById() is a method of the Mongoose model?

Question

What does findById do and is there documentation on it? I googled around a bit but didn't find anything.

Al Fahad
  • 2,378
  • 5
  • 28
  • 37
Legendre
  • 3,108
  • 7
  • 31
  • 46

4 Answers4

151

findById is a convenience method on the model that's provided by Mongoose to find a document by its _id. The documentation for it can be found here.

Example:

// Search by ObjectId
var id = "56e6dd2eb4494ed008d595bd";
UserModel.findById(id, function (err, user) { ... } );

Functionally, it's the same as calling:

UserModel.findOne({_id: id}, function (err, user) { ... });

Note that Mongoose will cast the provided id value to the type of _id as defined in the schema (defaulting to ObjectId).

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
9

If the schema of id is not of type ObjectId you cannot operate with function : findbyId()

Dasikely
  • 625
  • 7
  • 6
7

As opposed to find() which can return 1 or more documents, findById() can only return 0 or 1 document. Document(s) can be thought of as record(s).

Bonnie Varghese
  • 2,158
  • 1
  • 16
  • 11
4

I'm the maintainer of Mongoose. findById() is a built-in method on Mongoose models. findById(id) is equivalent to findOne({ _id: id }), with one caveat: findById() with 0 params is equivalent to findOne({ _id: null }).

You can read more about findById() on the Mongoose docs and this findById() tutorial.

vkarpov15
  • 3,614
  • 24
  • 21
  • I am getting the following error: `{ "message": "Cast to ObjectId failed for value \"{ id: '5d9a3b073f308e32b47a5cbb' }\" at path \"_id\" for model \"Categories\"", "name": "CastError", "stringValue": "\"{ id: '5d9a3b073f308e32b47a5cbb' }\"", "kind": "ObjectId", "value": { "id": "5d9a3b073f308e32b47a5cbb" }, "path": "_id" }` – Jasim Khan Afridi Oct 06 '19 at 20:15
  • 1
    Looks like you're passing in an object with an `id` property rather than a string or ObjectId instance. Try printing out `typeof val` and `val.constructor.name` to check what type you're actually passing in to `findById()` – vkarpov15 Oct 09 '19 at 16:08
  • I tried many combinations. Or may I say, all combinations. I do no have a property named `id`. I do no have the property of type `ObjectId`. – Jasim Khan Afridi Oct 11 '19 at 13:29
  • ok. found out my mistake. it was a silly one. i was passing id object as { id: 'blablabla' } instead of string... – Jasim Khan Afridi Oct 12 '19 at 22:43
  • @vkarpov15 Where can I find source of this `findById`? – rofrol Dec 10 '21 at 17:48