今天在做一个项目的时候发现,添加信息的时候会报错,但是一直找不到什么原因,一直报错
错误代码:
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,这样每次添加的时候就保证了只添加一个,没有导致冲突。