【问题标题】:Iterate mongoose object with EJS使用 EJS 迭代 mongoose 对象
【发布时间】: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);

正确的做法是怎样的?

【问题讨论】:

标签: javascript node.js mongodb express mongoose


【解决方案1】:

findasync 你需要从 Promise 中得到结果,这样做:

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

【讨论】:

    猜你喜欢
    • 2015-10-24
    • 2021-04-09
    • 2016-09-13
    • 2021-12-20
    • 1970-01-01
    • 2019-01-20
    • 2018-01-23
    • 2019-02-15
    • 2017-07-05
    相关资源
    最近更新 更多