dal dal - 1 year ago 109
Javascript Question

node js mongodb get data

I'm new in node js. I'm trying to get data from mongodb data, the data is stored perfectly. But when i want to get it back it's not working i'm using an array then i pass it to the html page, the elements of the array change only in loop for, after that i always get array.lengh equals to 1.

var express = require('express');
var async = require('express-async');
var MongoClient = require('mongodb');
var assert = require('assert');

var router = express.Router();


var url = "mongodb://localhost:27017/mydb";



router.get('/',function (req,res,next) {
aray = [{
FirstName: "da",
LastName: "m",
contry: "l"
}]
MongoClient.connect(url, function (err, db) {

if (err) throw err;
var cursor = db.collection('usercollection').find();

console.log("funBD")

cursor.each(function (err, doc) {
assert.equal(null, err);
console.log(doc);
if (doc != null)
aray.push(doc);
},function () {
db.close();
res.render('Profil',{items:aray});

});
});

});

module.exports = router;


the html page:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8" />
<style>
h1{
tab-size: 20;
text-align: center;
}
</style>

</head>
<body>
<% for(var i=0; i<items.length; i++) { %>
<li>
<%= items[i].FirstName %>
</li>
<% } %>

</body>
</html>


Thank you!

Answer Source

Try this code:

db.collection('usercollection').find().toArray(function (err, docs) {
    assert.equal(null, err);
    console.log(docs);
    aray = aray.concat(docs);

    db.close();
    res.render('Profil',{items:aray});
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download