Below is my smart contract:

#include <eosio/eosio.hpp>
#include <eosio/print.hpp>
#include <eosio/system.hpp>
#include <string>

using namespace eosio;
using std::string;

class [[eosio::contract("document")]] document : public eosio::contract {
                using contract::contract;
                document(name receiver, name code, datastream<const char*> ds):contract(receiver, code, ds) {}

        void erasedoc(name key) {
                            document_index documents( get_self(), get_first_receiver().value);
                            bool found = false;
                            for(auto itrer = documents.begin(); itrer != documents.end() && found!=true; itrer++) {
                                  if(itrer->key == key) {
                                          found = true;
                            check(found == false, "Document does not exist");
                struct [[eosio::table]] documenttable {
                        uint64_t doc_id;
                        name key;
                        std::string doc_name;
                        std::string doc_description;

                        uint64_t primary_key() const { return doc_id;}
                typedef eosio::multi_index<"documents"_n, documenttable> document_index;

doc_id is the primary key. But I want to delete the record using key. As, key is not the primary key I cannot use auto iterator = documents.find(key.value);. So, I implemented this logic. But this returns errors. Error:

Error 3160005: The table operation is not allowed
Error Details:
dereference of deleted object
pending console output:

Please help. How could I delete the record using key?


1 Answer 1


A secondary index sounds like a reasonable solution, depending on the amount and type of data stored but this should solve your problem as well.

if(itrer->key == key) {
    found = true;
    itrer = documents.erase(itrer);

Iterators are invalidated when erased which is why the error is thrown, but erase returns the next iterator so setting it should work.

  • This works, after I add secondary index and traverse using get_index. Used auto index = documents.get_index<name("bykey")>(); and for delete itrer = index.erase(itrer);.
    – Varsh
    May 31, 2021 at 2:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.