Tuesday 30 May 2017

Iterate mongoose object with EJS

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?



via Welp

No comments:

Post a Comment