简体   繁体   中英

How do you find by id using the MongoDB Node driver?

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.

_id字段已经建立索引,并且findByID隐式搜索一个文档,因此,在findOne中您将像现在那样在其中传递选项{_id: id}

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."

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