From my Node app I am trying to send a JSON array of MongoDB collection to client side HTML/AJAX. I want the Node.js data to reflect on a <select> or on a dropdown. The Node.js response object is sending 2 arrays hostArr and portArr I wish to concatenate the adjacent values and display it on select options. I have included my progress below, this for obvious reason doesn't work. Looking for a solution here..
app.js
MongoClient.connect(url,{ useUnifiedTopology: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("mongoDetails");
dbo.collection("mongoDetails").find({}).toArray(function(err, result) {
if (err) throw err;
var hostArr =[];
var portArr =[];
for(i=0;i<result.length;i++){
hostArr.push(result[i].hostname);
}
for(i=0;i<result.length;i++){
portArr.push(result[i].port);
}
console.log(hostArr);
console.log(portArr);
res.json({mongoDet1:hostArr, mongoDet2:portArr});
db.close();
});
});
Index.html
<div >
<select id="mongoDetails">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</select>
</div>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "http://localhost:8070/api/route1",
type: 'POST',
dataType:'json',
success: function(res) {
console.log(res);
$.each(res, function(key, value) {
console.log(key);
console.log(value);
$("#mongoDetails").value(res.mongoDet1[value]+res.mongoDet2[value]);
});
}
});
});
</script>