【问题标题】:associative array is removed in post request在发布请求中删除关联数组
【发布时间】:2018-03-15 11:39:57
【问题描述】:

我有一个带有一些属性和子属性的猫鼬模式。在版本属性上,我想要一个 Mixed 类型的子属性,因为我将向该属性发送不同的键/值对。但是将数据发送到node后,子属性为空,没有保存在MongoDB中。

这是我的架构

var Product = new mongoose.Schema({
    name: { 
        type: String
    },
    nameSlug: { 
        type: String
    },
    uploader: {
        _id: mongoose.Schema.Types.ObjectId,
        name: {
            type: String,
            required: true
        }
    },
    uploadDate: {
        type: Date,
        default: Date.now,
        required: true
    },
    dateLastModified: {
        type: Date,
        default: Date.now,
    },
    isBestseller: {
        type: Boolean,
        default: false,
        required: true
    },
    isVerified: {
        type: Boolean,
        default: false
    },
    suggestedRetailPrice: {
        type: Number
    },  
    brand: {
        _id: mongoose.Schema.Types.ObjectId,
        name: {
            type: String,
            required: true
        },
        nameSlug: {
            type: String,
            required: true
        },
        images: [Image]
    },
    productCollection: {
        type: String
    },
    category: {
        type: String,
        required: true
    },
    versions: [{
        author: [{
            name: String,
            _id: false
        }],
        date: {
            type: Date,
            required: true
        },
        concept: {
            type: Boolean,
            required: true
        },
        modifiedProperties: [mongoose.Schema.Types.Mixed],
        history: [{
            status: String,
            author: [{
                name: String,
                _id: false
            }],
            date: Date
        }]
    }]
}, {strict: false});

module.exports = mongoose.model('Product', Product);

图像一个现在不相关的子模式。在 versions 属性上,我有一个 modifiedProperties 属性,我想在我的 Angular 应用程序的更新中填充更改后的产品(名称、nameslug 等)属性。我按如下方式创建该对象

角度代码

var modifiedProperties = [];

angular.forEach($scope.addProductForm, function(value, key) {
    if(key[0] == '$') return;
    if(value.$dirty){
        modifiedProperties[key] = value.$$lastCommittedViewValue;
    }
});

var version = {
    author: {
        name: $rootScope.user.firstName + ($rootScope.user.lastNamePrefix ? " " + $rootScope.user.lastNamePrefix + " " : " ") + $rootScope.user.lastName,
        _id: $rootScope.user._id
    },
    date: new Date(),
    concept: true,
    modifiedProperties: modifiedProperties,
    history: {
        author: {
            name: $rootScope.user.firstName + ($rootScope.user.lastNamePrefix ? " " + $rootScope.user.lastNamePrefix + " " : " ") + $rootScope.user.lastName,
            _id: $rootScope.user._id
        },
        status: "Versie aangemaakt",
        date: new Date()
    }
}
console.log("VERSION", version);

var product = $scope.product;
product.versions.push(version);

$api.update('products/' + nameSlug, product)
    .then(function(response) {
        console.log("response", response);
    })
    .catch(function(reason) {
        console.log(reason);
})

在控制台中,我看到属性已正确填写,但在保存操作后,除了modifiedProperties 之外的所有内容都已保存。我在更新函数中放了一些日志,我看到的是modifiedProperties在控制器中是空的。我不知道他在哪里丢失了数据。 $api 服务是我们对 $http 函数的包装。数据没有松散,我们将使用data 字段发送。

控制器

module.exports.updateProduct = function(req, res) {
    console.log('[updateProduct controller]');

    /* This helper function can be called from elsewhere in the updateProduct controller and processes the HTTP response (and possibly errors) */
    function sendResponse(status, response, err) {

        /* Log HTTP response to the console server side before actually sending it to the client. */
        console.log(status + ' ' + response.message);

        /* Also log stack trace on error */
        if(err) {
            console.log('\nError message: ' + err);
            console.log(err.stack);
        }

        /* Send HTTP response */
        res.status(status).json(response);
    }

    if(req.params && req.params.nameSlug && req.body) {
        //Empty modifiedProperties (Array(0))
        console.log("REQ", req.body");
        let verifyProduct;
        if(req.body.verifyProduct && req.body.verifyProduct == true) {
            verifyProduct = true;
            delete req.body.verifyProduct;
        }
        console.log("PRODUCT", req.body);


        req.body.dateLastModified = Date.now();

        Product.findOneAndUpdate({nameSlug:req.params.nameSlug}, req.body, function (err, product) {

            /* Some error occurred while trying to update the product. */
            if(err) { 

                sendResponse(400, {message: 'Product could not be added. '}, err);

            /* The product doesn't exist */
            } else if(!product) {

                sendResponse(404, {message: 'Product not found. '});

            /* The product exists and has been updated successfully. */
            } else {

                /* Check if this product is being verified by an admin or not. If so, check if the admin is the same person who initially uploaded the product. */
                if(verifyProduct == true && product.uploader._id != req.user._id) {

                    /* If so, find that user to get their email adress. */
                    User.findById(product.uploader._id, function(err, user) {

                        /* An error occurred, so mailing the original uploader is not possible. */
                        if(err) {

                            sendResponse(200, {message: 'Product updated with errors. ', product}, err);

                        /* The original uploader does not exist (anymore), so sending mail is not possible. */
                        } else if(!user) {

                            sendResponse(200, {message: 'Product updated, but the uploader doesn`t seem to exist. ', product});

                        /* Send an email to the original uploader to notify them. */
                        } else {

                            var data = {
                                product: product,
                                user: user
                            };

                            var options = {
                                to: user.email,
                                subject: product.en.name + ' is toegevoegd aan PrismaNote!',
                                template: 'retailer-product-verified'
                            };

                            mailService.mail(options, data, null);
                            sendResponse(200, {message: 'Product updated. ', product});
                        }
                    });
                } else {
                    sendResponse(200, {message: 'Product updated. ', product});
                }
            }
        });
    }
};

有人知道这会出什么问题吗?或者为什么会这样?

编辑:

我看到数组modifiedProperties 的长度为“0”,因为键。这可能是nodejs不会处理它的原因吗?

【问题讨论】:

    标签: angularjs node.js mongodb


    【解决方案1】:

    嗯,我仍然不知道出了什么问题,但我已经解决了,将 modifiedProperties 直接传递给 product 而不是 product.versions。

    所以,我的 req.body 现在看起来像

    name: "testproduct",
    nameSlug: "testproduct",
    isBestseller: false,
    [other properties]
    modifiedProperties: {
       testfield: "testvalue",
       field2: "value2"
    },
    versions: {
        [
           date: [today],
           concept: true,
           [other properties]
        ],
        [
           date: [today],
           concept: true,
           [other properties]
        ],   
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-08
      • 2014-07-29
      • 1970-01-01
      • 2018-09-16
      • 1970-01-01
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多