从Node JS中的MongoDB查询中获取数据

时间:2018-01-03 07:50:13

标签: javascript node.js mongodb find response

我正在尝试从find()方法获取数据,以使用find()方法之外的数据。我想在JSON响应中使用数据。这段代码效果不好。数据未在find()方法之外定义。 如何在响应中使用数据?



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 个答案:

答案 0 :(得分:0)

做这个工作人员。代码不完整

var arrayOfProducts = [
  {..},
  {..}
];

function installProduct(product) {
  if(!product) {
    return;
  }

  var request = {
    method: 'POST',
    url: '..',
    data: product
  };

  return $http(request)
    .then(function() {
      var nextProduct = arrayOfProducts.shift();
      return installProduct(nextProduct);
    });
}

var firstProduct = arrayOfProducts.shift();
installProduct(firstProduct);

答案 1 :(得分:0)

如果不重新编写整个代码,我无法为您提供良好的答案。我在不同的文件中分离了应用程序的逻辑

<强> 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));