本文介绍了NodeJS + MongoDB:使用findOne()从集合获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个集合公司与几个对象。每个对象都有_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 没有这个公司的数据);
}
});
});
});

所以,我要求公司/ 4fcfd7f246e1464d05000001(4fcfd7f246e1464d05000001是我需要的对象的_id-parma)和findOne没有返回任何内容,为什么console.log('没有这个公司的数据');执行。



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



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

 _ id:{
$ oid:4fcfd7f246e1464d05000001
},

似乎有点奇怪...

解决方案

您需要构造ObjectID,而不是将其作为字符串传递。这样做应该可以工作:

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

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



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

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

而不是 createFromHexString 如上所述。


I have a collection "companies" with several objects. Every object has "_id" parameter. I'm trying to get this parameter from 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.

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

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

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

Seems to be strange a bit...

解决方案

You need to construct the ObjectID and not pass it in as a string. 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.

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

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

Instead of createFromHexString as outlined above.

这篇关于NodeJS + MongoDB:使用findOne()从集合获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 20:35