'trying to fetch the data in a nested arrays from mongodb in node js
trying to fetch the data in a nested arrays from mongodb in node js
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]);
}
})
});
}
Solution 1:[1]
You shouldn't connect to mongo in HTTP request callbacks, connect to it once and re-use that connection.
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);
});
Instead of looping over the cursor you can just call toArray, I recommend you don't format your data to a string on the server, instead pass the array back as JSON to the client and let the client render it out however it wants:
app.route('/results').get(async (req, res) => {
const { db } = req.app.locals;
const results = await db.collection('results').toArray();
res.status(200).json(results);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sagar |
