node js mongodb获取数据

时间:2017-07-26 22:06:21

标签: javascript node.js mongodb

我是节点js的新手。我正在尝试从mongodb数据中获取数据,数据存储完美。但是当我想要它回来它不工作我正在使用一个数组然后我将它传递给html页面,数组的元素只在循环中改变,之后我总是得到array.lengh等于1。 / p>

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; 

html页面:

<!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>    

谢谢!

1 个答案:

答案 0 :(得分:0)

试试这段代码:

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});
});