0

I'm working on a online shop project. I'm using Node.js, express.js and MongoDB with mongoose. I got the product information from the MongoDB database and sending them to the client side. In my case, I can get all these data in my client side but before sending, when I print them to the console in server side, it says undefined.

This is the products schema:

var schema = new Schema({
    imagePath: {
        type: String,
        required: true
    },
    productName: {
        type: String,
        required: true
    },
    productPrice: {
        type: Number,
        required: true
    },
    productCategory: {
        type: String,
        required: true
    },
    productShortInformation: {
        type: String,
        required: true
    },
    productFullInformation: {
        type: String,
        required: true
    },
    productViews: {
        type: Number,
        required: false
    },
    productStock: {
        type: Number,
        required: true
    }
});

and here is my Node.js code

router.get('/category/summary', function(req, res, next) {
    //getting my all products information
    var products = Product.find(function (err, docs) {
        if(err) {
            console.log('Error Happened'  + err);
            return res.redirect('/');
        } else {
            //HERE IS THE PROBLEM
            //ALL PRODUCT NAME IS SHOWN UNDEFINED
            //BUT WHEN I SEND THEM TO THE CLIENT, I GET PRODUCT NAME
            for(var product in docs) {
                console.log('Name: ' + product.productName);
            }

            res.render('shop/categorySummary', {
                products: docs  //sending these information to the client side
            });
        }
    });
});

When I try to print these product name, I get undefined. But in the client side I can print the product information.

I need to manipulate these data before sending them to the client side. So how can I print these product information to the server side(in console) before sending?

1 Answer 1

3
for(var product in docs) {
     console.log('Name: ' + docs[product].productName);
}

That should work

Sign up to request clarification or add additional context in comments.

2 Comments

OMG, Thank you very much. It's working. Thanks a lot.
@BMShamsNahid On Stack Overflow we say thank you by accepting answers which helped us. There's a green checkmark next to the answer on the left which you tick :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.