如何将嵌套数组推入节点js中的mongo db

时间:2017-07-02 06:21:29

标签: javascript node.js mongodb mongoose

我正在尝试 POST 使用mongoose将产品数据发送到mongo db。
产品型号

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var productsSchema = new Schema({
  //  productId: {type: _id, required: true, autoIndex: true},
    merchantId: {type: String, required: true},
    productName: {type: String, required: true},
    productDescription: {type: String, required: true},
    uploadDate: {type: Date, default: Date.now},
    productAttributes: [
        {
            size: {type: Number, required: true},
            colors: [
                {
                    color: {type: String, required: true},
                    qty: {type: Number, required: true},
                    price: {type: Number, required: true},
                    images: [{
                        image1: {type: String, required: true},
                        image2: {type: String, required: false},
                        image3: {type: String, required: false}
                    }]
                }

            ]
        }
    ],
    otherAttributes: {
        length: {type: Number, required: false},
        fabricType: {type: Number, required: false},
        sleeves: {type: String, required: false}

    }
});


CreateProductMethod

module.exports.createProduct = function (product, callback) {
    var newProduct = new Products();
    newProduct.merchantId = product.merchantId;
    newProduct.productName = product.productName;
    newProduct.productDescription = product.productDescription;
    newProduct.productAttributes.size = product.productAttributes.size;
    newProduct.productDescription.colors.color=product.productAttributes.colors.color;
    newProduct.productDescription.colors.qty=product.productAttributes.colors.qty;
    newProduct.productDescription.colors.price=product.productAttributes.colors.price;
    newProduct.productDescription.colors.images.image1=product.productAttributes.colors.image1;

    Products.create(newProduct, callback);
}; <br/>

当** POSTING 数据到服务器时我收到此异常无法在Function.module.exports.createProduct 中读取未定义的属性'颜色' 为什么我收到此错误?

请帮助。

1 个答案:

答案 0 :(得分:0)

你有几个错误

  1. newProduct.productDescription是一个字符串,您无法为newProduct.productDescription.size
  2. 指定值
  3. product.productAttributes.size所需的索引必须为product.productAttributes[0].size或使用forEach循环迭代
  4. product.productAttributes.colors.color;所需的索引必须为product.productAttributes[0].colors[0].color;或使用forEach循环迭代