简体   繁体   English

我正在尝试使用 nodejs 从 mongodb 集合中检索数据,但我必须请求两次才能获得正确的信息

[英]I am trying to retrieve data from mongodb collection using nodejs but i have to request it twice to get the correct information

This is my code: I have to request twice to get the data.这是我的代码:我必须请求两次才能获取数据。 Any problem?任何问题? Thanks谢谢

var http = require('http');
var url = require('url');
var input = "";
const MongoClient = require('mongodb').MongoClient;
const url2 = "mongodb+srv://ramaty01:password@cluster0-hi4fv.mongodb.net/test?retryWrites=true&w=majority";

http.createServer(function(req, res){
  if (req.url === '/favicon.ico') {
    res.writeHead(200, {'Content-Type': 'image/x-icon'} );
    res.end();
    console.log('favicon requested');
    return;
  }
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write(
    "<html><head><title> MongoDB and NodeJS</title></head>" + 
    "<body><h1> COMPANY STOCK STICKER</h1><form>" + 
      "<input type='radio' id='company' name='types' value='company' required>" +
      "<label for='company'>Company Name</label><br>" + 
      "<input type='radio' id='stock' name='types' value='stock'>" + 
      "<label for='stock'>Stock Ticker</label><br><br>" +
      "<label for='txt'>Input: </label>" +
      "<input type='text' id='txt' name='txt'><br><br>" +
      "<input type='submit' value='Submit'>" +
    "</form><div id='output'></div></body></html>"
  );
  var qobj = url.parse(req.url, true).query;

  //var items;
  mong(qobj);
  res.write(input);
  res.end()
  input= "";
}).listen(8080);

function mong(qobj){

MongoClient.connect(url2, { useUnifiedTopology: true }, function(err, db) {
    if(err) { console.log("Connection err: " + err); return; }
    var dbo = db.db("Company");
    var coll = dbo.collection('companies');
    var query;
    var inp = qobj.txt;
    if (qobj.types == "company") {
      query = { "company_name" : inp};
    } else if (qobj.types == "stock") {
      query = { "stock_ticker" : inp};
    }
    var s = coll.find(query,{projection: {"company_name":1, "stock_ticker":1, "_id":0}}).stream();

    s.on("data", function(item) {input = input + item.company_name + " " + item.stock_ticker;});
    s.on("end", function() {console.log("end of data");  db.close();});
  });
}


First of all, I recommend that you immediately change your monogdb atlas password, and that you be more careful next time you're posting anything with sensitive information online.首先,我建议您立即更改您的monogdb atlas 密码,并且下次您在网上发布任何包含敏感信息的内容时要更加小心。

With that being said, having worked with mongodb Atlas for sometime now, I've noticed that connection normally takes sometime, and that introduces some noticeable lag the fist time you fire up your server.话虽如此,在与 mongodb Atlas 合作一段时间后,我注意到连接通常需要一些时间,并且在您启动服务器时会引入一些明显的延迟。 That is probably what is happening, and since from your code I can't see evidence that your local server is waiting for this connection to happen before "serving" requests to your browser, there is no guarantee of the succession of events To test this hypothesis, I suggest you wait for sometime before accessing the local server.这可能是正在发生的事情,并且由于从您的代码中我看不到证据表明您的本地服务器正在等待此连接发生,然后再向您的浏览器“提供”请求,因此无法保证事件的连续性要测试这一点假设,我建议您在访问本地服务器之前等待一段时间。 This can be easily solved using an async function, or chaining a promise before starting your local server这可以使用异步 function 或在启动本地服务器之前链接 promise 轻松解决

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试从JSON文件中检索数据,但是我无法从特定属性中检索信息 - I am trying to retrieve data from a JSON file, but I am having trouble retrieving information from a specific property 我正在尝试使用NodeJS从JSON数据中提取某些值 - I am trying to extract certain values from JSON data with NodeJS 我正在尝试从 firebase 中的单个键中检索数据 - I am trying to retrieve data from a single key in firebase 我正在尝试使用javascript从MongoDB查找这种特定日期格式的数据 - I am trying to find data in this specific format of date from MongoDB using javascript 我正在尝试执行GET / POST请求,并两次定义了options变量。 第二个定义覆盖第一个 - I am trying to do a GET/POST request and defined the options variable twice. The second definition overrides the first 单击图像时,我正在尝试从 Sharepoint 列表中检索信息 - I am trying to retrieve information from a Sharepoint list when clicking an image 我正在尝试从 2 个数组中检索结果 - I am trying to retrieve result from 2 array 我正在尝试使用 nodejs 在 mongodb 中使用填充,但没有填充值 - I am trying to use populate in mongodb with nodejs, but values are not populating 我可以在NodeJS中正确使用请求模块吗? - Am I correctly using the request module in NodeJS? 当我从 mongoDB 检索数据时它可以工作但是当我通过 NodeJS 将它发送到客户端时它返回一个错误 - When i retrieve data from mongoDB it works but when i send it to client via NodeJS it returns an error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM