简体   繁体   English

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

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

I have a collection "companies" with several objects.我有一个包含多个对象的“公司”集合。 Every object has "_id" parameter.每个对象都有“_id”参数。 I'm trying to get this parameter from db:我正在尝试从 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');因此,我请求公司/4fcfd7f246e1464d05000001(4fcfd7f246e1464d05000001 是我需要的对象的 _id-parma)并且 findOne 什么都不返回,这就是为什么 console.log('no data for this company'); executes.执行。

I'm absolutely sure that I have an object with _id="4fcfd7f246e1464d05000001".我绝对确定我有一个 _id="4fcfd7f246e1464d05000001" 的对象。 What I'm doing wrong?我做错了什么? Thanks!谢谢!

However, I've just noticed that id is not a typical string field.但是,我刚刚注意到 id 不是典型的字符串字段。 That's what mViewer shows:这就是 mViewer 显示的内容:

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

Seems to be strange a bit...好像有点奇怪……

You need to construct the ObjectID and not pass it in as a string.您需要构造 ObjectID 而不是将其作为字符串传入。 Something like this should work:这样的事情应该工作:

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 Ohad in the comments (thanks Ohad!), you can also use:编辑:正如Ohad在评论中指出的(感谢 Ohad!),您还可以使用:

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

Instead of createFromHexString as outlined above.而不是上面概述的createFromHexString

That's because _id field in mongo isn't of string type (as your req.params.id ).那是因为 mongo 中的_id字段不是string类型(如您的req.params.id )。 As suggested in other answers, you should explicitly convert it.正如其他答案中所建议的那样,您应该明确转换它。

Try mongoskin , you could use it like node-mongodb-native driver, but with some sugar.试试mongoskin ,你可以像 node-mongodb-native 驱动程序一样使用它,但要加点糖。 For example:例如:

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

You can use findById() which will take care of the id conversion for you.您可以使用findById()它将为您处理 id 转换。

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

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

}

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

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