R01010010
R01010010

Reputation: 5958

Simple query by _id with mongoose and node.js not working

objective:

Find one document from mongodb by its _id.

Environment:

JavaScript, Node.js, Mongoose

So i have this code... (here a portion of an "Post" Schema)

PostSchema.statics = {
   findById: function (id, cb) {
       this.findOne({ _id : { $eq: mongoose.Types.ObjectId(id) } }).exec(cb);
   }
}

And then this other code calling this method:

var Post = mongoose.model('Post');
Post.findById('54986a8b43db661a0ec827e4', function(result){
     console.log(result);
});

I get the error: Can't use $eq with ObjectId

I tried the query db.posts.find({_id: {$eq: ObjectId('54986a8b43db661a0ec827e4')}}); directly in mongodb engine and it works, but not in mongoose...

So i don't know what to do for querying just by an id!

Upvotes: 0

Views: 4205

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

It's not working because $eq is an aggregation operator. Just use a direct comparison instead:

PostSchema.statics = {
   findById: function (id, cb) {
       this.findOne({ _id : id }).exec(cb);
   }
}

You don't need to make an ObjectId out of id as Mongoose will do that casting for you.

But you don't even need to create this method yourself as the built-in findById method does the same thing.

Upvotes: 1

Related Questions