2017-05-30 3 views
1

<%= products %>を私のビューに入れると[Object Object]が表示されるので、mongoose resultsetがオブジェクトであると仮定しています。さて、私はproductsオブジェクトをループしようとしていますが、それはproducts.forEach is not a functionと言います。EJSでmongooseオブジェクトを反復する

これは私の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) { %> 
 
    \t <p><%= product.title %></p> 
 
    <% }); %> 
 
    </body> 
 
</html>
最後に、これは私の Product Schema

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

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

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

どのようにそれを行うための適切な方法はありますか?

+1

'()を見つける'非同期..ですあなたが結果を得るために約束を必要とする。.. 関連します。https:/ /stackoverflow.com/questions/6180896/how-to-return-mongoose-results-from-the-find-method – Pogrindis

答えて

1

findは、あなたがこのようにそれを行うの約束から生じる取得する必要がありますasyncです:

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

素晴らしい!ありがとうございました – Welp

関連する問題