EasyFreeNotes
EasyFreeNotes

Reputation: 17

ReferenceError: product is not defined

I'm trying to fetch the data , but when i console it.I' getting the data but in rendering it's not working in front end its showing product is not defined.

app.get('/profile/profile/dashboard/update/:id',function (req,res,next) {
           //console.log("hello "+req.params.id);
    Product.findOne({_id: req.params.id}).then(product=>{

        console.log("hello check please "+ product);
    });

    res.render('update.ejs',{ product: product });
});

update.ejs file

<% if (product._id) { %>
        <tbody>
        <td><input type="text" value="<%= product.name %>" required></td>
        <td><input type="text" value="" required></td>
        <td><input type="text" value="" required></td>
        <td><input type="text" value="" required></td>
        <td><input type="submit" class="btn btn-danger" value="submit"></td>
        </tbody>
        <% } %>

Upvotes: 0

Views: 4155

Answers (2)

shankar singh rajput
shankar singh rajput

Reputation: 523

Yes problem with your code is rendering is placed outside of the find one method. Put it inside the braces like.

app.get('/profile/profile/dashboard/update/:id',function (req,res,next) {
           //console.log("hello "+req.params.id);
    Product.findOne({_id: req.params.id}).then(product=>{

        console.log("hello india "+ product);
        res.render('update.ejs',{ product: product });
    });
});

Upvotes: 0

Ron537
Ron537

Reputation: 990

The problem is that you are trying to render the data before the findOne is finished. findOne is asynchronic function and that is why the log works for you.

Move res.render inside the then scope:

Product.findOne({_id: req.params.id}).then(product=>{

        console.log("hello check please "+ product);
        res.render('update.ejs',{ product: product });
    });

Upvotes: 1

Related Questions