【发布时间】:2017-10-30 23:38:58
【问题描述】:
当我将<%= products %> 放入我的视图时,它会打印 [Object Object] 所以我假设猫鼬结果集是一个对象。现在,我正在尝试遍历 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 JSONerror。
这是我的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()是异步的.. 你需要一个承诺才能得到结果.. 相关:stackoverflow.com/questions/6180896/…
标签: javascript node.js mongodb express mongoose