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.
connect('mongodb://localhost/Company'); var Schema = new mongoose. Schema({ _id : String, name: String, age : Number }); var user = mongoose. model('emp', Schema); app. param('id', function(req, res, next, id){ user.
To create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the correct ip address and the name of the database you want to create. MongoDB will create the database if it does not exist, and make a connection to it.
Every document in the collection has an “_id” field that is used to uniquely identify the document in a particular collection it acts as the primary key for the documents in the collection. “_id” field can be used in any format and the default format is ObjectId of the document.
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!
Following is the example which spots the issue:
var mongo = require('mongodb'),
Server = mongo.Server,
Db = mongo.Db,
ObjectID = require('mongodb').ObjectID;
var MongoClient = require('mongodb').MongoClient
//let id = your _id, smth like '6dg27sh2sdhsdhs72hsdfs2sfs'...
var obj_id = new ObjectID('52cbd028e9f43a090ca0c1af');
var justId = '52cbd028e9f43a090ca0c1af'; // <== This will not work
MongoClient.connect('mongodb://127.0.0.1:27017/YourDbName', function(err, db) {
console.log('err' + err);
db.collection('YourCollectionName', function(error, collection) {
//collection.find({_id:justId}),function(err, docs) { // <== This will not work
collection.findOne({_id:obj_id},function(err, docs) {
console.log("Printing docs from Array. count " + JSON.stringify(docs));
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With