【问题标题】:Mongoose / MongoDB duplicate entries with unique key in schemaMongoose / MongoDB 在模式中具有唯一键的重复条目
【发布时间】:2021-09-09 16:15:07
【问题描述】:

我不知道为什么会发生这种情况,我有一个带有字段“地址”的唯一键的架构,但我得到了重复的条目。我还在插入新文档之前检查 Model.exists() 是否仍然插入文档。我不知道为什么,我也偶尔会在控制台中遇到重复输入错误。这是我的代码

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);
        }
    }

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    为了防止 mongodb 中的重复条目,您可以在该特定字段上添加唯一索引。在这种情况下:db.collection.createIndex({"address":1},{unique:true}) 。 参考:https://docs.mongodb.com/manual/core/index-unique/

    【讨论】:

    • 但我已经有一个具有唯一属性的字段:true 显示为地图集上的索引。那不可能,你看到我上面的架构了吗?
    • 再次添加它的唯一方法是如果它进入 if(!exists) 条件,这意味着 Address.exists() 没有按预期工作?也许尝试用 findOne() 或 countDocuments() 替换。
    猜你喜欢
    • 2012-02-19
    • 1970-01-01
    • 2015-07-13
    • 2023-03-10
    • 1970-01-01
    • 2022-01-24
    • 2018-04-14
    • 1970-01-01
    • 2017-11-17
    相关资源
    最近更新 更多