Mongoosejs can't query with findById Mongoosejs can't query with findById mongoose mongoose

Mongoosejs can't query with findById


The problem is that you need to define a schema for your model to tell Mongoose that your _id field is a String instead of the standard ObjectId in this collection:

AccountSchema = new mongoose.Schema    _id: String    profile:        available: BooleanAccount = mongoose.model 'users', AccountSchema


Seems that your _id field isn't an ObjectId. The method findById on Mongoose expects:

id objectid, or a value that can be casted to one

So, if your _id in fact isn't an ObjectId, you should query using findOne method

account = Account.findOne { "_id" : req.params.account_id }


The currently propagated answer is not a good idea. Don't change the schema for your model to tell Mongoose that your _id field is a String. That is a bad idea in terms of validation and should be considered a hack.

Try this instead:If you want to query for an _id in mongoose, you have to cast the _id to ObjectId

AccountSchema = new mongoose.Schema({    _id: ObjectID(),    profile: {        available: Boolean    });Account = mongoose.model('users', AccountSchema);

Mongoosejs requires you to cast the id in the query as well (I didn't find anything about this in the mongoose documentation either):

account = Account.findOne({ "_id" : mongoose.Types.ObjectId(req.params.account_id) });