MST

星途 面试题库

面试题:CouchDB设计文档验证函数的复杂业务扩展

假设在一个CouchDB数据库中有一个表示订单的文档结构,其中包含'order_items'数组,每个数组元素是一个包含'product_id'、'quantity'和'price'的对象。现有一个基本的设计文档验证函数,要求扩展它,确保订单总金额(所有商品quantity * price之和)不超过1000,且每个商品的'quantity'大于0。请详细阐述实现步骤并给出完整代码。
29.3万 热度难度
数据库CouchDB

知识考点

AI 面试

面试题答案

一键面试
  1. 实现步骤

    • 遍历order_items数组。
    • 检查每个order_items元素中的quantity是否大于0。
    • 计算每个商品的金额(quantity * price)并累加到总金额。
    • 检查总金额是否超过1000。
  2. 完整代码

function validate(doc) {
    if (doc.type === 'order') {
        let totalAmount = 0;
        for (let item of doc.order_items) {
            if (item.quantity <= 0) {
                throw({forbidden: "Quantity of each item must be greater than 0"});
            }
            totalAmount += item.quantity * item.price;
        }
        if (totalAmount > 1000) {
            throw({forbidden: "Total order amount cannot exceed 1000"});
        }
    }
}

在CouchDB设计文档中,上述函数通常会作为验证函数使用,确保写入数据库的订单文档满足指定的规则。例如,在创建或更新订单文档时,CouchDB会调用此验证函数进行检查。如果验证不通过,会抛出异常并阻止文档的保存。