簡體   English   中英

試圖從 node.js 中的 mongodb 獲取嵌套 arrays 中的數據

[英]trying to fetch the data in a nested arrays from mongodb in node js

試圖從 node.js 中的 mongodb 獲取嵌套 arrays 中的數據

 exports.cities = async (req, res, next) => { MongoClient.connect(url, function (err, db) { if (err) res.send(err); let dbo = db.db(DATABASE); const { country_code, state_code } = req.body; dbo.collection("countries").find({iso2:country_code}).toArray(function (err, result) { //res.json(result); for(let i=0; i<result.length; i++){ for(let j=0; j<result[i].states.state_code.length; j++){ if(result[i].states[j].state_code == result[AP]){ res.json(result[i].states[j]) } } //res.json(result[i]); } }) }); }

在此處輸入圖像描述

您不應該在 HTTP 請求回調中連接到 mongo,連接一次並重新使用該連接。

const mongoClient = new MongoClient(url, { useNewUrlParser: true });

mongoClient.connect((err) => {
  if (err) throw err;

  // Available via req.app.locals.db.
  app.locals.db = mongoClient.db('your-database');

  app.listen(3000); 
});

你可以調用toArray而不是遍歷 cursor ,我建議你不要將數據格式化為服務器上的字符串,而是將數組作為 JSON 傳遞回客戶端並讓客戶端根據需要呈現它:

app.route('/results').get(async (req, res) => {
  const { db } = req.app.locals;
  const results = await db.collection('results').toArray();
  res.status(200).json(results);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM