From 86535e24aa8aa1523480336ae57e7fdf885f0bb2 Mon Sep 17 00:00:00 2001 From: Kishore Nallan Date: Sun, 5 Feb 2023 13:20:02 +0530 Subject: [PATCH] Improve error message for nested array object string field. --- src/index.cpp | 8 ++++++++ test/collection_nested_fields_test.cpp | 25 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/index.cpp b/src/index.cpp index f599eab6..c3db97b7 100644 --- a/src/index.cpp +++ b/src/index.cpp @@ -5557,6 +5557,10 @@ Option Index::coerce_string(const DIRTY_VALUES& dirty_values, const st else { if(dirty_values == DIRTY_VALUES::COERCE_OR_DROP) { if(!a_field.optional) { + if(a_field.nested && item.is_array()) { + return Option<>(400, "Field `" + field_name + "` has an incorrect type. " + "Hint: field inside an array of objects must be an array type as well."); + } return Option<>(400, "Field `" + field_name + "` must be " + suffix + " string."); } @@ -5568,6 +5572,10 @@ Option Index::coerce_string(const DIRTY_VALUES& dirty_values, const st } } else { // COERCE_OR_REJECT / non-optional + DROP + if(a_field.nested && item.is_array()) { + return Option<>(400, "Field `" + field_name + "` has an incorrect type. " + "Hint: field inside an array of objects must be an array type as well."); + } return Option<>(400, "Field `" + field_name + "` must be " + suffix + " string."); } } diff --git a/test/collection_nested_fields_test.cpp b/test/collection_nested_fields_test.cpp index 997026a7..87a58145 100644 --- a/test/collection_nested_fields_test.cpp +++ b/test/collection_nested_fields_test.cpp @@ -1445,6 +1445,31 @@ TEST_F(CollectionNestedFieldsTest, ExplicitSchemaOptionalFieldValidation) { } } +TEST_F(CollectionNestedFieldsTest, ExplicitSchemaForNestedArrayTypeValidation) { + nlohmann::json schema = R"({ + "name": "coll1", + "enable_nested_fields": true, + "fields": [ + {"name": "blocks.text", "type": "object[]"}, + {"name": "blocks.text.description", "type": "string"} + ] + })"_json; + + auto op = collectionManager.create_collection(schema); + ASSERT_TRUE(op.ok()); + Collection* coll1 = op.get(); + + auto doc1 = R"({ + "blocks": {"text": [{"description": "Hello world."}]} + })"_json; + + auto add_op = coll1->add(doc1.dump(), CREATE); + + ASSERT_FALSE(add_op.ok()); + ASSERT_EQ("Field `blocks.text.description` has an incorrect type. " + "Hint: field inside an array of objects must be an array type as well.", add_op.error()); +} + TEST_F(CollectionNestedFieldsTest, SortByNestedField) { nlohmann::json schema = R"({ "name": "coll1",