Skip to content

Commit 5286814

Browse files
committed
change mongo _id transformation to fix filtering
1 parent 4118cce commit 5286814

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

adminforth/dataConnectors/mongo.ts

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,10 @@ class MongoConnector extends AdminForthBaseConnector implements IAdminForthDataS
8282
} else if (field.type == AdminForthDataTypes.DECIMAL) {
8383
return value?.toString();
8484
} else if (field.name === '_id' && !field.fillOnCreate) {
85-
// if "_id" was created by mongo it will be ObjectId
86-
return value?.toString();
85+
// value is supposed to be an ObjectId or string representing it
86+
if (typeof value === 'object') {
87+
return value?.toString();
88+
}
8789
}
8890

8991
return value;
@@ -107,8 +109,20 @@ class MongoConnector extends AdminForthBaseConnector implements IAdminForthDataS
107109
} else if (field.type == AdminForthDataTypes.DECIMAL) {
108110
return Decimal128.fromString(value?.toString());
109111
} else if (field.name === '_id' && !field.fillOnCreate) {
110-
// if "_id" was created by mongo it supposed to be saved as ObjectId
111-
return ObjectId.createFromHexString(value);
112+
// value is supposed to be an ObjectId
113+
if (!ObjectId.isValid(value)) {
114+
return null;
115+
}
116+
if (typeof value === 'string' || typeof value === 'number') {
117+
// if string or number - turn it into ObjectId
118+
return new ObjectId(value);
119+
} else if (typeof value === 'object') {
120+
// assume it is a correct ObjectId
121+
return value;
122+
}
123+
124+
// unsupported type for ObjectId
125+
return null;
112126
}
113127
return value;
114128
}
@@ -203,7 +217,8 @@ class MongoConnector extends AdminForthBaseConnector implements IAdminForthDataS
203217

204218
async updateRecordOriginalValues({ resource, recordId, newValues }) {
205219
const collection = this.client.db().collection(resource.table);
206-
await collection.updateOne({ [this.getPrimaryKey(resource)]: recordId }, { $set: newValues });
220+
const primaryKeyColumn = resource.dataSourceColumns.find((col) => col.name === this.getPrimaryKey(resource));
221+
await collection.updateOne({ [primaryKeyColumn.name]: this.setFieldValue(primaryKeyColumn, recordId) }, { $set: newValues });
207222
}
208223

209224
async deleteRecord({ resource, recordId }): Promise<boolean> {

0 commit comments

Comments
 (0)