对象或数组中对象的count属性的问题

时间:2017-04-24 08:16:46

标签: javascript node.js

我尝试计算另一个对象的属性但是得到一个错误的值:我想计算订单对象的productInfo属性中的对象,该对象是15但我的函数返回46。

router.get("/product", isLoggedIn, function (req, res) {
    products.find({}, function (err, products) {
        if (err) {
            console.log("ERROR!");
        } else {
            orders.find({
                customerInfo: req.user
            }, function (err, orders) {
                if (err) {
                    console.log("ERROR!");
                } else {
                    res.render("allProduct", {
                        data1: _.keys(orders[0].productInfo).length,//here object must counted!
                        data:products
                    });
                }
            });
        }
    });
});

以下是我的模特:

var mongoose = require("mongoose");

var order = new mongoose.Schema({
    orderNo: Number,
    customerInfo: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        }],
    productInfo: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: "product"
        },]
});

//EXPORT
module.exports = mongoose.model("order", order);

var mongoose =require("mongoose");

var product = new mongoose.Schema({
    productNo: Number,
    productName: String,
    productDes:String,
    productPrice:Number,
});

//EXPORT
module.exports = mongoose.model("product",product);

1 个答案:

答案 0 :(得分:0)

I solve this issues with replace :

_.keys(orders[0].productInfo).length,

with:

orders[0].productInfo.length