mongodb出现E11000 duplicate key error collection(id重复的解决)

今天在做一个项目的时候发现,添加信息的时候会报错,但是一直找不到什么原因,一直报错在这里插入图片描述
错误代码:

File “D:\Aanconda_install\lib\site-packages\pymongo\helpers.py”, line 198, in _raise_last_write_error

raise DuplicateKeyError(error.get("errmsg"), 11000, error)

pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: sjjy.sjjy index: id dup key: { : ObjectId(’’) }

主要原因是同时插入数据造成 _id 重复

<template>
  <div>
    <h1>{{ id ? "修改" : "添加" }}分类</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="上级分类">
        <el-select v-model="model.parent" placeholder="请选择">
          <el-option
            v-for="item in parents"
            :key="item.value"
            :label="item.name"
            :value="item._id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="input.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    id: { type: String },
  },
  async created() {
    await this.fetchparents();
    if (this.id) {
      const result = await this.$http.get(`rest/categories/${this.id}`);
      this.model = result.data;
      console.log(result);
    } else {
      const result = await this.$http.get(`rest/categories`);
      this.model = result.data;
    }
  },
  data() {
    return {
      input: {},
      model: {},
      needToRemove: {},
      parents: [],
    };
  },
  methods: {
    async fetchparents() {
      const result = await this.$http.get(`rest/categories`);
      this.parents = result.data;
    },
    async save() {
      if (this.id) {
        const res = await this.$http.put(
          `rest/categories/${this.id}`,
          this.model
        );
        console.log(res);
      } else {
        const res = await this.$http.post("rest/categories", this.input);
        console.log(res);
      }
      this.$router.push("/categories/list");
      this.$message({
        type: "success",
        message: "保存成功",
      });
    },
  },
};
</script>

代码中通过打印req.body发现里面有两个数据,所以导致同时插入,解决的办法是对输入框单独绑定一个数据input,这样每次添加的时候就保证了只添加一个,没有导致冲突。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值