面试题答案
一键面试-
实现步骤:
- 遍历
order_items
数组。 - 检查每个
order_items
元素中的quantity
是否大于0。 - 计算每个商品的金额(
quantity * price
)并累加到总金额。 - 检查总金额是否超过1000。
- 遍历
-
完整代码:
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会调用此验证函数进行检查。如果验证不通过,会抛出异常并阻止文档的保存。