用EJS迭代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(); 但没有运气。 另一个我试过的解决scheme是使用这个代码:

  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你需要从诺言得到的结果这样做:

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