MongoDB/Realm添加文档数组元素时出现“backfilling nulls in array of links are not supported”错误的原因及含义解析
MongoDB/Realm 数组添加元素报错的成因与解析
我来帮你拆解这个错误的来龙去脉,先把关键信息理清楚:
你的问题场景
你在MongoDB/Realm环境中尝试给CompanyLocation集合里的文档的units数组添加新元素,确认待添加的元素引用在数据库中存在,但触发了同步错误,报错信息和你的代码如下:
错误信息
["To resolve this issue please update or replace the document in MongoDB to make sure it abides by the schema.", "Change Event Type: update", "Namespace: app.CompanyLocation", "Partition: dag1f7g7102aecdd3e9467711e", "Document ID: ObjectID(\"61f7f74a2aecdd3e9467711f\")", "Detailed Error: cannot insert link at index 7 of array at path { table: \"CompanyLocation\", fullPath: \"units\" }, array has 6 elements and backfilling nulls in array of links are not supported", "Number of Unsyncable Documents: 1"]
触发错误的代码
const newUnits = result.Shipment.Units[0].Unit.map(u => u._attributes.UID + u._attributes.PSN).flat(); console.log(newUnits); if(importResult.success){ // Lägg till den som inventory på platsen. context.services.get("mongodb-atlas") .db("app") .collection("CompanyLocation") .updateOne( { _id: new BSON.ObjectId(place), _partition: partition}, { $push: { units: { $each: newUnits } } } ) console.log(newUnits); }
错误成因与具体含义解析
核心错误原因
这个错误的根源在于Realm对「链接数组(Array of Links)」的严格约束:
你的units字段在Realm Schema中被定义为链接数组(即数组中的每个元素都是指向其他MongoDB文档的引用),而Realm不允许这种类型的数组存在「空洞」——也就是数组中间不能有null元素,同时也不支持为了填充指定索引位置而自动补null。
错误信息逐句解读
To resolve this issue please update or replace the document in MongoDB to make sure it abides by the schema.:你的操作导致文档违反了Realm的Schema规则,需要修复文档使其符合要求才能同步。Change Event Type: update:触发错误的是一个文档更新操作(也就是你执行的updateOne)。Namespace: app.CompanyLocation:操作的是app数据库下的CompanyLocation集合。Partition: dag1f7g7102aecdd3e9467711e:对应的Realm分区键值,用于隔离同步数据。Document ID: ObjectID("61f7f74a2aecdd3e9467711f"):具体出错的文档ID。- Detailed Error(核心错误):你试图往一个只有6个元素的
units数组的第7个索引位置(数组索引从0开始,原数组索引范围是0-5)插入链接元素,但Realm不允许通过填充null来补全中间缺失的索引位置(这里是索引6),因此操作失败。 Number of Unsyncable Documents: 1:有1个文档因为违反Schema规则,无法和Realm客户端同步。
为什么你的$push操作会触发这个错误?
正常来说$push + $each是往数组末尾追加元素,不会指定索引,那为什么会出现插入到索引7的情况?大概率是因为:
你之前对这个units数组执行过直接设置指定索引的操作(比如$set: { "units.7": someDocumentId }),MongoDB会自动扩展数组并将中间未设置的索引位置填充为null,但Realm的链接数组不允许存在null,导致数组处于「非法状态」。现在你再执行$push操作时,Realm的同步逻辑检测到数组存在空洞,进而触发这个错误。
内容的提问来源于stack exchange,提问作者Olle Thunberg
相关产品推荐
相关产品推荐

