<Node.js Mongoskin集合迭代>玉

时间:2014-06-16 17:58:39

标签: javascript node.js mongodb express pug

我正在尝试通过集合迭代创建一个目录并通过jade向用户显示,但tableContent每次运行都是'No Orders',即使很难,我认为我已经正确设置了db。 / p>

“listing.js”用于迭代db集合并将其发送给jade

var express = require('express');
var router = express.Router();

var mongo = require('mongoskin'); 
var db = mongo.db("mongodb://localhost:27017/db", {native_parser:true});

var iterateOrders = function() {
  var tableContent = ''; //TableContent Array
  db.collection('orders').find({}, function(err, result) {
    result.each(function(err, order) {
      tableContent += '<tr>';
      tableContent += '<td>' + this.orderID + '</td>';
      tableContent += '<td>' + this.receiverName + '</td>';
      tableContent += '<td>' + this.receiverAddress + '</td>';
      tableContent += '<td>' + this.receiverEmail + '</td>';
      tableContent += '<td>' + this.order + '</td>';
      tableContent += '</tr>';
      });
    });
    if (tableContent === '') {tableContent = 'No Orders';}
    return tableContent;
  }

router.get('/', function(req, res) {
  res.render('listing', { 
    title: 'Orderlist:', 
    table: iterateOrders() });
});

module.exports = router;

我已使用“mongo”

手动写入数据库
  

db.orders.insert({ '的orderID' ... EN'})

我的玉器实现

block content
  table
    thead
      th #
      th Name
      th Addr
      th Email
      th Order
    tbody= table

1 个答案:

答案 0 :(得分:1)

使用return关键字返回值不会在异步调用中工作。您需要在回调中传递值。这是代码:

var express = require('express');
var router = express.Router();

var mongo = require('mongoskin'); 
var db = mongo.db("mongodb://localhost:27017/db", {native_parser:true});

var iterateOrders = function(callback) {
  var tableContent = ''; //TableContent Array
  db.collection('orders').find({}).toArray(function(err, result) {
    for (var i = 0, len = result.length; i < len; i++) {
      tableContent += '<tr>';
      tableContent += '<td>' + result[i].orderID + '</td>';
      tableContent += '<td>' + result[i].receiverName + '</td>';
      tableContent += '<td>' + result[i].receiverAddress + '</td>';
      tableContent += '<td>' + result[i].receiverEmail + '</td>';
      tableContent += '<td>' + result[i].order + '</td>';
      tableContent += '</tr>';
    }
    if (tableContent === '') {tableContent = 'No Orders';}
    callback(null, tableContent);
  });
}

router.get('/', function(req, res) {
  iterateOrders(function(err, tableContent) {
    res.render('listing', { 
      title: 'Orderlist:', 
      table: tableContent
    });
  });
});

module.exports = router;