Wednesday, 17 May 2017

How do I pass the data from MongoDB to my web api through node.js?

I am trying to load my data in the web api by using postman to test it out. So I am able to get my query right on console.log(doc) on node.js but when i tried to return callback and post on postman, it gives me [object Object]and does not give back the data itself just object. This is my code.

 var MongoClient = require('mongodb').MongoClient;
 var assert = require('assert');
 var url = 'mongodb://localhost:27017/myproject';

module.exports = {

postCollection : function(req, res){
    var issueQty = req.body.issueQty;
    var itemDescrip = req.body.itemDescrip;
MongoClient.connect(url, function(err, db) {
    assert.equal(null, err);
    updateRecord(db, req, function(doc) {
    res.send('Record Found. Now updating this document...' + itemDescrip + ' 
    Record Updated. This is the new record '
    + doc )
    db.close();
    });

});
}
}
 var updateRecord = function(db, req, callback) {
var cursor = db.collection('documents').find({'Item Description': 
req.body.itemDescrip, 'Issued QTY': req.body.issueQty})
cursor.each(function(err,doc){
   assert.equal(err,null);
     if(doc != err){
         console.log('Successfully queried');
         console.log(doc);
         return callback(doc);

     } else{
         callback(doc);
     }
 });
 db.collection('documents').updateMany(
  { 'Item Description': req.body.itemDescrip},
  {
    $set: { 'Issued QTY': req.body.issueQty }
  }      
  /*function(err, results) {
    console.log(results);
    console.log('Done');
});*/
)};

So right now I am lost as to where I have done wrong to output [object Object] instead of the queried data. Any help is appreciated, thanks!



via Ong Kong Tat

No comments:

Post a Comment