简体   繁体   English

如何使用MongoDB节点驱动程序按ID查找?

[英]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 . 我正在寻找使用MongoDB Node驱动程序按ID查找的最佳方法。

I see that the _id field is an ObjectId , and so using a string for the id won't work. 我看到_id字段是一个ObjectId ,因此使用字符串作为id无效。 And I see that you could use ObjectId as follows: 而且我看到您可以如下使用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);
  });
};

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. 注意:猫鼬有一个findById方法,您可以在其中使用id字符串。

_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?). 据我了解,主要的设计考虑因素是使本机驱动程序API与mongo shell体验相似,并在各处保持一致(其他驱动程序也一样)。 For this purpose you might want to keep API simple, yet powerful to cover all cases. 为此,您可能希望使API保持简单,但功能强大以涵盖所有情况。 So, to generalize, you have find() method and "a db.collection.findOne() method as a special case of find() that returns a single document." 因此,概括地说,您具有find()方法和“作为返回单个文档的find()的特例的db.collection.findOne()方法”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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