简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM