javascript - 用 EJS 迭代 Mongoose 对象

标签 javascript node.js mongodb express mongoose

当我输入 <%= products %>在我看来,它打印 [Object Object] 所以我假设 mongoose 结果集是一个对象。现在,我正在尝试遍历 products对象,但它说 products.forEach is not a function .

这是我的 index route :

var express = require('express');
var router = express.Router();
var Product = require('../model/product');

/* GET home page. */
router.get('/', function(req, res, next) {
  var products = Product.find();
  res.render('index', { title: 'Express', products: products });
});

module.exports = router;

使用上面的代码,我只是从数据库中检索它并将其作为对象传递。我试过使用 var products = Product.find({}).toArray();但没有运气。我尝试的另一个解决方案是使用此代码:

  var products = Product.find();
  var data = JSON.stringify(products);
  res.render('index', { title: 'Express', products: data });
但我得到了臭名昭著的Converting circular structure to JSON错误。

这是我的 index view :

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
  <h1><%= title %></h1>
  <p>Welcome to <%= title %></p>

  <% products.forEach(function(product) { %>
  	<p><%= product.title %></p>
  <% }); %>
  </body>
</html>
最后这是我的 Product Schema :

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var schema = new Schema({
	imagePath: { type: String, required: true },
	title: { type: String, required: true },
	description: { type: String, required: true },
	price: { type: Number, required: true }
});

module.exports = mongoose.model('Product', schema);

正确的做法是什么?

最佳答案

findasync 你需要从 promise 中得到结果,这样做是这样的:

router.get('/', function(req, res, next) {
  Product.find({}, function(err, products) {
      res.render('index', { title: 'Express', products: products });
  });
});

关于javascript - 用 EJS 迭代 Mongoose 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44263202/

相关文章:

node.js - Node 监视器错误 : "System limit for number of file watchers reached"

javascript - 函数返回不起作用

mongodb - 如何使用 --auth 选项运行 flapdoodle MongodStarter

javascript - 为订阅框创建透明背景

node.js - 使用 nvm 卸载当前事件的 node.js 版本

javascript - 检查JS中是否有任何键按下

linux - node.js ftdi 模块抛出错误 : libftd2xx. 所以:无法打开共享对象文件

javascript - 使用 Node.js、Express 和 MongoDB 通过 ISODate 查找

javascript - Angular JS - 该程序根本没有运行

javascript - javascript 中的正则表达式换行?