Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

node.js - NodeJS + MongoDB: Getting data from collection with findOne ()

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...