diff --git a/src/collection.cpp b/src/collection.cpp index 862a2c22..f8439897 100644 --- a/src/collection.cpp +++ b/src/collection.cpp @@ -82,6 +82,12 @@ Option Collection::add(const std::string & json_str) { } std::string doc_id = document["id"]; + Option doc_option = get(doc_id); + + // we need to check if document ID already exists before attempting to index + if(doc_option.ok()) { + return Option(400, std::string("A document with id ") + doc_id + " already exists."); + } const Option & index_memory_op = index_in_memory(document, seq_id); diff --git a/test/collection_test.cpp b/test/collection_test.cpp index b939792e..8f0501ca 100644 --- a/test/collection_test.cpp +++ b/test/collection_test.cpp @@ -1479,6 +1479,15 @@ TEST_F(CollectionTest, IndexingWithBadData) { ASSERT_FALSE(bad_token_ranking_field_op4.ok()); ASSERT_STREQ("Bad JSON.", bad_token_ranking_field_op4.error().c_str()); + // should return an error when a document with pre-existing id is being added + std::string doc = "{\"id\": \"100\", \"name\": \"foo\", \"age\": 29, \"tags\": [], \"average\": 78}"; + Option add_op = sample_collection->add(doc); + ASSERT_TRUE(add_op.ok()); + add_op = sample_collection->add(doc); + ASSERT_FALSE(add_op.ok()); + ASSERT_EQ(400, add_op.code()); + ASSERT_STREQ("A document with id 100 already exists.", add_op.error().c_str()); + collectionManager.drop_collection("sample_collection"); }