如何在Cosmos DB中覆盖已有文档?Node.js SDK实现方案
Cosmos DB Node.js SDK:处理重复ID文档的覆盖需求
问题描述
我使用以下代码可以正常创建文档:
this.container.items .create<Session>(data) .then(() => callback(null)) .catch((error) => { console.log("error >>>", error) callback(error) });
但当尝试创建具有相同ID的文档时,会收到错误:
message: 'Entity with the specified id already exists in the system.'
请问是否可以让Cosmos忽略该错误并覆盖现有文档,或者Node.js SDK中有对应的方法?
解决方案
1. 使用upsert方法(推荐)
SDK自带的upsert方法正好满足「存在则覆盖,不存在则创建」的需求,直接替换原代码中的create即可:
this.container.items .upsert<Session>(data) .then(() => callback(null)) .catch((error) => { console.log("error >>>", error) callback(error) });
这个方法会自动处理文档的存在性判断,无需额外写错误捕获逻辑。
2. 捕获错误后调用replace方法
如果需要自定义错误处理逻辑,可以捕获create抛出的409错误(ID重复的错误码),再调用replace方法覆盖现有文档:
this.container.items .create<Session>(data) .then(() => callback(null)) .catch((error) => { if (error.code === 409) { // 需传入文档ID和对应的分区键(如果容器有分区键) this.container.item(data.id, data.partitionKey) .replace<Session>(data) .then(() => callback(null)) .catch(replaceError => { console.log("replace error >>>", replaceError) callback(replaceError) }); } else { console.log("error >>>", error) callback(error) } });
注意:使用replace时必须指定正确的分区键,否则会因找不到文档而报错。
内容的提问来源于stack exchange,提问作者Rodrigo
相关产品推荐
相关产品推荐

