你如何使用MongoDB Node驱动程序找到id?

时间:2015-07-03 23:30:01

标签: node.js mongodb

我正在寻找使用MongoDB Node driver按ID查找的最佳方式。

我发现_id字段是ObjectId,因此使用字符串表示ID无法正常工作。我看到你could use ObjectId如下:

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);
  });
};

但是有最好的做法/更便捷的方式吗?在查看文档时我没有遇到过。注意:Mongoose有一个findById方法,您只需使用id字符串。

2 个答案:

答案 0 :(得分:1)

_id字段已经编入索引,并且findByID会隐式搜索一个文档,因此,findOne您将在其中传递选项{_id: id}

答案 1 :(得分:0)

据我所知,主要的设计考虑因素是使本机驱动程序API与mongo shell体验类似,并使其在所有地方保持一致(其他驱动程序也是如此?)。为此,您可能希望保持API简单,但功能强大,以涵盖所有情况。因此,为了概括,您有find()方法和"a db.collection.findOne() method as a special case of find() that returns a single document."