0

I am trying to fetch data from find() method, to use the data outside the find() method. I want to use the data in JSON response. This code didn't work well. The data is not defined outside the find() method. HOW COULD I USE THE DATA IN THE RESPONSE?

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

MongoClient.connect(url,function(err,db){
  assert.equal(err,null);

 db.collection("adchar").find(
    { target_gender: 'female' },
    {ad_path:1,ad_direct:1, _id:0}).toArray(function(err,docs){
      callback(docs);
      assert.equal(err,null);
      path =docs[0].ad_path;
      direct =docs[0].ad_direct;
                  }); 
     });
  

exports.get = function(req, res) {  
res.writeHead(200 , { 'content-Type':'application/json'})
var myObj = {
AdUrl:path
,dirURL : direct, 
};
res.end(JSON.stringify(myObj));
};

2
  • Is this the full code that you have? At what point does your exports.get method get invoked? Commented Jan 3, 2018 at 8:09
  • No this is not the full code, the exports.get method in router.js file. Commented Jan 3, 2018 at 9:11

2 Answers 2

1

I can't provide you a good answer without refatcoring your whole code. I've separate the logic of the app in different files

db.js

const { MongoClient } = require('mongodb');

// these variables are not set until the connecion is established, any attempt
// to use them before that will, most likely, throw an error;
exports.client = undefined;
exports.database = undefined;
exports.adCharCollection = undefined;

exports.connect = async function connect(host, dbName) {
  exports.client = await MongoClient.connect(host);
  exports.database = exports.client.db(dbName);
  exports.adCharCollection = exports.database.collection("adchar");
}

model.js

const db = require('./db');

exports.getResults = async function getResults(gender) {
  const docs = db.adCharCollection
    .find({ target_gender: gender }, { ad_path: 1, ad_direct: 1, _id: 0 })
    .limit(1)
    .toArray();

  if (!docs.length) {
    return null;
  }

  const doc = docs[0];

  return { AdUrl: doc.ad_path, dirURL: doc.ad_direct };
}

controller.js

const { getResults } = require('./model');

exports.get = async function get(req, res) {
  try {
    const result = await getResults("female");

    res.writeHead(200, { "content-Type": "application/json" });
    res.end(JSON.stringify(result));
  } catch (err) {
    res.writeHead(500, { "content-Type": "application/json" });
    res.end(JSON.stringify({
      error: true,
      message: err.message,
      stack: err.stack.split('\n') // the stack only for development purposes
    }));
  }
}

server.js

const http = require('http');
const { connect } = require('./db');
const { get } = require('./controller');

const PORT = 3000;
const MONGO_HOST = 'mongodb://localhost:27017';
const MONGO_DB = 'serverad';

async function main() {
  // we first need to connect to mongo before doing anything
  await connect(MONGO_HOST, MONGO_DB);

  // set the request handler
  const server = http.createServer(get);

  await new Promise((resolve, reject) => {
    server.listen(PORT, (err) => {
      if (err) {
        reject(err);
        return;
      }

      console.log(`server running at http://localhost:${PORT}/`);
      resolve();
    });
  });

  return server;
}

main().catch(err => console.log(err.stack));
Sign up to request clarification or add additional context in comments.

Comments

0

Do this staff . The code is incomplete

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

var fetchData =  function(callback){

MongoClient.connect(url,function(err,db){
  assert.equal(err,null);

 db.collection("adchar").find(
    { target_gender: 'female' },
    {ad_path:1,ad_direct:1, _id:0}).toArray(function(err,docs){
      callback(err ,docs);
      assert.equal(err,null);
      path =docs[0].ad_path;
      direct =docs[0].ad_direct;
                  }); 
     });
}; 

exports.get = function(req, res) {  

fetchData (function(error,result){
    if(error){
        // do error staff here
    } else{
    res.writeHead(200 , { 'content-Type':'application/json'})
    var myObj = {
    AdUrl:path
    ,dirURL : result, 
    };
    res.end(JSON.stringify(myObj));
    }
});

};

5 Comments

Thank you, there the data appear, but in incorrect format- see the next comment -,It must be as JSON file output.
{"AdUrl":"","dirURL":[{"ad_path":"i.pinimg.com/736x/5d/35/74/…"}]}
can you tell me when you print myObj what you get ?
The output in the previous comment, but now I try to print result[0] , and it is work well, as I need. Thanks for all who help me.
Marks the answer if you get you solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.