当我输入 <%= 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);
正确的做法是什么?
最佳答案
find
是 async
你需要从 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/