Question
Variable not defined in EJS template
<input class="form-control" type="text" name="name" value="<%= product.name %>" placeholder="name">
product is not defined
This is my route file:
const express = require('express')
const router = express.Router()
const imageMimeTypes = ['image/jpeg', 'image/png', 'images/gif']
//GET product model
var Product = require('../models/product')
//GET Category model
var Category = require('../models/category')
//GET All product Page
router.get('/', async(req, res) => {
let query = Product.find()
if (req.query.name != null && req.query.name != '') {
query = query.regex('name', new RegExp(req.query.name, 'i'))
}
try {
const products = await query.exec()
res.render('admin/products', {
products: products,
searchOptions: req.query
})
} catch {
res.redirect('/')
}
});
//GET category page
router.get('/add-product', async(req, res) => {
res.render('admin/add_product')
});
//POST Add page
router.post('/', async(req, res) => {
const product = new Product({
name: req.body.name,
category: req.body.category,
price: req.body.price,
shopName: req.body.shopName,
district: req.body.district,
productCount: req.body.productCount,
description: req.body.description
})
saveCover(product, req.body.cover)
try {
const newProduct = await product.save()
// res.redirect(`products/${newProduct.id}`)
res.redirect(`products`)
} catch {
renderNewPage(res, products, true)
}
});
async function renderNewPage(res, products, hasError = false) {
try {
const categories = await Category.find({})
const params = {
categories: categories,
product: product
}
if (hasError) params.errorMessage = 'Error Adding Product'
res.render('admin/add_product', params)
} catch {
res.redirect('/products')
}
}
function saveCover(book, coverEncoded) {
if (coverEncoded == null) return
const cover = JSON.parse(coverEncoded)
if (cover != null && imageMimeTypes.includes(cover.type)) {
product.productImage = new Buffer.from(cover.data, 'base64')
product.productImageType = cover.type
}
}
module.exports = router;
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
×
@sasisp2000 Can you provide some more context here? On what page is this error occurring? What code surrounds the line that is erroring? What does your product model look like (what does the find method return)?