Mongoose / MongoDB duplicate entries with unique key in schema

I dont know why this happens, I have a schema with a unique key for the field "address" but I get duplicate entries. I also check before I insert a new document if Model.exists() and it still inserts documents. I have no idea why, also I am getting occasional duplicate entry errors in the console. This is my code

const Schema = mongoose.Schema(
    {
        address    : { type: String, unique: true },
        isContract : { type: Boolean, required: true, default: false },
        ethervalue : { type: Number, default: 0 },
        symbol     : { type: String, unique: true },
        tokenname : { type: String},
        divisor   : { type: Number },
        tokentype : {type: String},
        bluecheckmark: {type : Boolean, default: false},
        description: {type: String},
        totalsupply: {type: Number},
    },
    { timestamps: true }
);
async saveAddress(address) {
        try {
            const exists = await Address.exists({ address: address });
            if (!exists) {
                const isContract = await this.isContract(address);
                let temp = new Address();
                if (isContract) {
                    const info = await etherscan.getTokenInfoByContractAddress(address);
                    temp.isContract = true;
                    if(info.status == 1){       
                        temp.symbol = info.result[0].symbol;
                        temp.tokenname = info.result[0].tokenName;
                        temp.totalsupply = info.result[0].totalSupply;
                        temp.divisor =  info.result[0].divisor;
                        temp.tokentype = info.result[0].tokenType;
                        temp.description = info.result[0].description
                        temp.bluecheckmark = info.result[0].blueCheckmark
                    }
                }

                temp.address = address;
                await temp.save();
            }
        } catch (error) {
            console.log('saveAddres()', error.message);
        }
    }


from Recent Questions - Stack Overflow https://ift.tt/3zZYaFF
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation