mongoose: findById returns no results even with correct ObjectId

Configuration: Mongoose 4.0.5, MongoDb 3.0.4, Node 0.12.4 Issue does not appear on Mongoose 3.8.30

My database has the following data:

db.users.find()
{ "_id" : ObjectId("5580c79aa11e7310b2985ab1"), "email" : "an_email", "color" : "", "username" : "", "__v" : 0 }

I query it with Mongoose using the following syntax:

User.findById("5580c79aa11e7310b2985ab1", function(error, user) { }

which returns null for both error and user. Strangely enough Mongoose’s debugging shows the following, correct query:

users.findOne({ _id: ObjectId("5580c79aa11e7310b2985ab1") })

which queried directly on MongoDB finds the expected data:

db.users.findOne({ _id: new ObjectId("5580c79aa11e7310b2985ab1") })
{
    "_id" : ObjectId("5580c79aa11e7310b2985ab1"),
    "email" : "an_email",
    "color" : "",
    "username" : "",
    "__v" : 0
}

I tried various alternatives such as directly initializing an ObjectId object or taking an ObjectId from a find() result which leads to no results either. As stated above reverting back to Mongoose 3.8 resolves the issue.

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 2
  • Comments: 33

Most upvoted comments

mongoose = require(‘mongoose’).set(‘debug’, true);

Use this so you can see what query mongoose are sending to the database. It helped me when I had the same problem as you. In my case, mongoose was sending the collection name in plural.

I was having very same issue as @florianheinemann and @nafisto . The strange thing was that I could use findand findById on other models without any problem. Finally I managed to found out that mongoose uses my collection User as users. It is lowercasing and adding s to the end (They say that this behaviour is smart). Anyway I had to force collection name to model and schema as shown below in bold. That fixed the issue for me.

var userSchema = mongoose.Schema({ email: { type: String }, passwordEnc: { value : String, version: String, salt : String }, nameFirst : String, nameLast : String, phone : String, dob : String },{collection: ‘User’});

var User = mongoose.model(‘User’, userSchema, ‘User’);

Aw sorry, copy-paste error from a test I ran at the command line. Should be this:

User.find({ _id: '55822f34a8394683dd015888' });         // returns empty array
User.findOne({ _id: '55822f34a8394683dd015888' });      // returns null

thanks JonatasCV, that “debug” option saved my day

Check in mongodb and make sure that your time _id fields are all ObjectIds rather than plain strings