NodeJS + MongoDB:使用 findOne() 从集合中获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10929443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:50:32  来源:igfitidea点击:

NodeJS + MongoDB: Getting data from collection with findOne ()

node.jsmongodbexpress

提问by f1nn

I have a collection "companies" with several objects. Every object has "_id" parameter. I'm trying to get this parameter from db:

我有一个包含多个对象的“公司”集合。每个对象都有“_id”参数。我正在尝试从 db 获取此参数:

app.get('/companies/:id',function(req,res){
db.collection("companies",function(err,collection){
    console.log(req.params.id);
    collection.findOne({_id: req.params.id},function(err, doc) {
        if (doc){
            console.log(doc._id);
        } else {
            console.log('no data for this company');
        }
    });
});
});

So, I request companies/4fcfd7f246e1464d05000001 (4fcfd7f246e1464d05000001 is _id-parma of a object I need) and findOne returns nothing, that' why console.log('no data for this company'); executes.

因此,我请求公司/4fcfd7f246e1464d05000001(4fcfd7f246e1464d05000001 是我需要的对象的 _id-parma)并且 findOne 什么都不返回,这就是为什么 console.log('no data for this company'); 执行。

I'm absolutely sure that I have an object with _id="4fcfd7f246e1464d05000001". What I'm doing wrong? Thanks!

我绝对确定我有一个 _id="4fcfd7f246e1464d05000001" 的对象。我做错了什么?谢谢!

However, I've just noticed that id is not a typical string field. That's what mViewer shows:

但是,我刚刚注意到 id 不是典型的字符串字段。这就是 mViewer 显示的内容:

"_id": {
        "$oid": "4fcfd7f246e1464d05000001"
    },

Seems to be strange a bit...

好像有点奇怪……

回答by Adam Comerford

You need to construct the ObjectID and not pass it in as a string. Something like this should work:

您需要构造 ObjectID 而不是将其作为字符串传入。这样的事情应该工作:

var BSON = require('mongodb').BSONPure;
var obj_id = BSON.ObjectID.createFromHexString("4fcfd7f246e1464d05000001");

Then, try using that in your find/findOne.

然后,尝试在您的 find/findOne 中使用它。

Edit: As pointed out by Ohadin the comments (thanks Ohad!), you can also use:

编辑:正如Ohad在评论中指出的(感谢 Ohad!),您还可以使用:

new require('mongodb').ObjectID(req.params.id)

Instead of createFromHexStringas outlined above.

而不是createFromHexString如上所述。

回答by Aleksei Zabrodskii

That's because _idfield in mongo isn't of stringtype (as your req.params.id). As suggested in other answers, you should explicitly convert it.

那是因为_idmongo 中的字段不是string类型(如您的req.params.id)。正如其他答案中所建议的那样,您应该明确转换它。

Try mongoskin, you could use it like node-mongodb-native driver, but with some sugar. For example:

试试mongoskin,你可以像 node-mongodb-native 驱动程序一样使用它,但要加点糖。例如:

// connect easier
var db = require('mongoskin').mongo.db('localhost:27017/testdb?auto_reconnect');

// collections
var companies = db.collection('companies');

// create object IDs
var oid = db.companies.id(req.params.id);

// some nice functions…
companies.findById();

//… and bindings
db.bind('companies', {
  top10: function(callback) {
    this.find({}, {limit: 10, sort: [['rating', -1]]).toArray(callback);
  } 
});

db.companies.top10(printTop10);

回答by darren

You can use findById()which will take care of the id conversion for you.

您可以使用findById()which 将为您处理 id 转换。

company = Company.findById(req.params.id, function(err, company) {
    //////////
});

回答by matteo_dm

In case these didn't work for you, this worked for me for accessing a blog post:

如果这些对您不起作用,这对我访问博客文章有用:

const getSinglePost = async (req, res) => {

    let id = req.params.id;
    var ObjectId = require('mongodb').ObjectId;
    const db = await client.db('CMS');

    const data = await db.collection("posts").findOne({ _id: ObjectId(id) })

    if (data) {
        res.status(200).send(data)
    } else res.status(400).send({ message: "no post found" })

}