2

When i put <%= products %> into my view, it prints [Object Object] so I'm assuming that the mongoose resultset is an object. Now, I am trying to loop over products object but it says products.forEach is not a function.

This is my 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;

with the code above,I am just retrieving it from the db and passing it as an object. I have tried using var products = Product.find({}).toArray(); but got no luck. And another solution I tried is using this code:

  var products = Product.find();
  var data = JSON.stringify(products);
  res.render('index', { title: 'Express', products: data });
but I am getting the infamous Converting circular structure to JSONerror.

This is my 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>
lastly this is my 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);

How is the proper way of doing it?

Welp
  • 357
  • 1
  • 5
  • 17
  • 1
    `find()` is async.. You need a promise to get the results .. related : https://stackoverflow.com/questions/6180896/how-to-return-mongoose-results-from-the-find-method – Pogrindis May 30 '17 at 13:16

1 Answers1

2

find is async you need to get result from promise do it like this:

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