【问题标题】:How to print data, retrieved from mongoDB database in Node.js?如何打印从 Node.js 中的 mongoDB 数据库中检索的数据?
【发布时间】:2017-01-08 15:23:44
【问题描述】:

我正在开发一个在线商店项目。我将 Node.js、express.js 和 MongoDB 与猫鼬一起使用。我从 MongoDB 数据库中获取产品信息并将它们发送到客户端。就我而言,我可以在客户端获取所有这些数据,但在发送之前,当我将它们打印到服务器端的控制台时,它显示未定义。

这是产品架构:

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
    }
});

这是我的 Node.js 代码

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
            });
        }
    });
});

当我尝试打印这些产品name 时,我得到了不确定。但是在客户端我可以打印产品信息。

我需要在将这些数据发送到客户端之前对其进行操作。那么如何在发送之前将这些产品信息打印到服务器端(在控制台中)?

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongodb-query


    【解决方案1】:
    for(var product in docs) {
         console.log('Name: ' + docs[product].productName);
    }
    

    应该可以的

    【讨论】:

    • 天啊,非常感谢。它正在工作。非常感谢。
    • @BMShamsNahid 在 Stack Overflow 上,我们通过 accepting answers which helped us 表示感谢。您勾选的左侧答案旁边有一个绿色复选标记:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 2019-06-14
    • 2015-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多