Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Querying a MongoDB based on Mongo ID in a node.js app

I'm using a node.js and mongodb, and I'm trying to query the database based on the mongo generated ID using the following:

    collection.findOne( {_id:doc._id} , function(err, item) {});

I am 100% certain that my doc._id is an exact match to the doc _id that I am looking for in the collection, and yet I get a null response from the db query.

I have tried this using other keys in the document and it returns the document just fine. It's only when I try to use the mongo ID.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The MongoDb is an object not a string. To convert my string I used:

    var id = require('mongodb').ObjectID(doc._id);

This converts my string into a mongo ObjectId and matches the _id in the db!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...