在post请求中删除了associative数组

时间:2017-10-04 06:55:49

标签: angularjs node.js mongodb

我有一个带有一些属性和子属性的mongoose模式。在版本属性上我想要一个具有Mixed类型的子属性,因为我将向此属性发送不同的键/值对。但是在将数据发送到节点之后,子属性为空并且不会保存在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应用程序的更新中填充更改的产品(名称,名称符号等)属性。我创建该对象如下

角度代码

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不会处理它的原因吗?

1 个答案:

答案 0 :(得分:0)

嗯,我还不知道出了什么问题,但我已经解决了这个问题,将modifiedProperties直接传递给了产品,而不是产品。逆转。

所以,我的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]
    ],   
}