简体   繁体   English

节点js mongodb获取数据

[英]node js mongodb get data

I'm new in node js. 我是Node JS的新手。 I'm trying to get data from mongodb data, the data is stored perfectly. 我正在尝试从mongodb数据中获取数据,数据已完美存储。 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. 但是,当我想找回它不起作用时,我正在使用一个数组,然后将其传递给html页面,该数组的元素仅在循环中更改,之后我总是得到array.lengh等于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: 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>    

Thank you! 谢谢!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM