【问题标题】:Fetch data from MongoDB query in Node JS从 Node JS 中的 MongoDB 查询中获取数据
【发布时间】:2018-01-03 07:50:12
【问题描述】:

我正在尝试从 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));
};

【问题讨论】:

  • 这是您拥有的完整代码吗?你的exports.get 方法在什么时候被调用?
  • 不,这不是完整的代码,router.js 文件中的exports.get 方法。

标签: javascript node.js mongodb find response


【解决方案1】:

如果不对您的整个代码进行重构,我无法为您提供一个好的答案。我已将应用程序的逻辑分开在不同的文件中

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 谢谢,出现了数据,但格式不正确-见下一条评论-,必须是JSON文件输出。
    • {"AdUrl":"","dirURL":[{"ad_path":"i.pinimg.com/736x/5d/35/74/…"}]}
    • 你能告诉我当你打印myObj你得到了什么吗?
    • 上一条评论中的输出,但现在我尝试打印 result[0] ,它工作得很好,正如我所需要的。感谢所有帮助我的人。
    • 如果您得到解决方案,请标记答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 2019-05-11
    • 1970-01-01
    相关资源
    最近更新 更多