Reputation: 19238
I'm looking for the best way to find by id using the MongoDB Node driver.
I see that the _id
field is an ObjectId
, and so using a string for the id won't work. And I see that you could use ObjectId as follows:
var ObjectId = require('mongodb').ObjectId;
exports.show = function(req, res) {
var db = req.app.get('db');
var id = new ObjectId(req.params.id);
db.collection('posts').findOne({
_id: id
}, function(err, post) {
res.status(200).json(post);
});
};
But is there a best practice/more convenient way? I hadn't come across one in looking through the docs. Note: Mongoose has a findById method where you could just use the id string.
Upvotes: 1
Views: 2901
Reputation: 1155
As far as I understand, the major design consideration was to make native driver API similar to the mongo shell experience and keep it consistent all over the place (other drivers as well?). For this purpose you might want to keep API simple, yet powerful to cover all cases. So, to generalize, you have find()
method and "a db.collection.findOne() method as a special case of find() that returns a single document."
Upvotes: 0
Reputation: 3445
The _id field is already indexed, and findByID implicitly searches for one document, hence, findOne
where you'll pass options {_id: id}
as you're already doing.
Upvotes: 1