-1

I am use MongoClient = require('mongodb').MongoClient; module in NodeJs. But, i have not get single row JSON Object result in node. I have no any idea in mongodb client module.

Simple Query: select *from settings where id=1;

Mongo Query: db.collection("settings").findOne({_id:"5860cdf634c39399937f6619"});

I have get multiple JSON row like:

mongo.client.connect(mongo.url, function(err, db){
        var resultArr = [];
        var data = db.collection("settings").find();
        data.forEach(function(doc, err){
            mongo.assert.equal(null, err);
            resultArr.push(doc);
        }, function(){
            db.close();
            res.json({error:false,data:resultArr,msg:""});
        });
    });

This is working fine. But, i have not able to get single row.

I am use this library : http://mongodb.github.io/node-mongodb-native/2.2/installation-guide/

Bharat Chauhan
  • 3,204
  • 5
  • 39
  • 52

1 Answers1

1

I have resolve my own error!. using this reference link: Querying a MongoDB based on Mongo ID in a node.js app

My Old code:

exports.getById = function(req, res, next) {
    mongo.client.connect(mongo.url, function(err, db){
        var id = req.params.id; // "5860cdf634c39399937f6619"           
        var data = db.collection("settings").findOne({_id:id}).then(function(doc) {
            console.log(doc);
            db.close();
        });
    });
};

See my resolved code:

exports.getById = function(req, res, next) {
    mongo.client.connect(mongo.url, function(err, db){
        var id = req.params.id;
        var o_id = mongo.ObjectId(id); // this is my solutions
        var data = db.collection("settings").findOne({_id:o_id}).then(function(doc) {
            console.log(doc);
            db.close();
        });
    });
};
Community
  • 1
  • 1
Bharat Chauhan
  • 3,204
  • 5
  • 39
  • 52