有没有人在MEVN堆栈中组合了他们的编辑和创建表单?例如,Moongoose的保存方法可以创建或更新,但我不确定如果ID存在或不存在,您将如何处理传入ID。下面是我目前的创建过程和更新过程。将两个不同的组件组合成一个完成两项工作的组件会很好。
CreateStudent.vue
handleSubmitForm() {
console.log("handleSubmitForm")
this.isSubmitted = true;
let apiURL = "http://localhost:4000/api/create-student";
axios
.post(apiURL, this.student)
.then(() => {
this.$router.push("/list");
this.student = {
firstName: "",
lastName: "",
email: "",
phone: "",
password: "",
confirmPassword: "",
};
//alert("SUCCESS! " + JSON.stringify(this.userForm));
})
.catch((error) => {
console.log(error);
})
.finally((next) => {
// console.log('is Submiited);
})
},
studentRoute.route("/create-student").post((req, res, next) => {
StudentModel.create(req.body, (error, data) => {
if (error) {
return next(error);
} else {
res.json(data);
}
})
})
字符串
EditStudent.vue
handleUpdateForm() {
let apiURL = `http://localhost:4000/api/update-student/${this.$route.params.id}`;
axios.post(apiURL, this.student).then((res) => {
console.log(res)
this.$router.push('/list')
}).catch(error => {
console.log(error)
});
}
studentRoute.route('/update-student/:id').post((req, res, next) => {
StudentModel.findByIdAndUpdate(req.params.id, {
$set: req.body
}, (error, data) => {
if (error) {
return next(error);
} else {
res.json(data)
console.log('Student successfully updated!')
}
})
})
型
2条答案
按热度按时间4szc88ey1#
根据文档,你可以简单地发送一个选项来findByIdAndUpdate,其中一个是upsert
[options.upsert=false]如果为true,且未找到文档,则插入新文档
https://mongoosejs.com/docs/api/model.html#Model.findByIdAndUpdate()
比如说
字符串
应该既作为更新又作为插入
pprl5pva2#
最好是分别处理更新和创建。@Bergur是正确的,因为
findOneAndUpdate
和findByIdAndUpdate
有一个upsert
选项,允许您在没有匹配文档的情况下更新或插入。但是,根据我的经验,这通常在最初工作,然后问题开始。关键的症结是验证。对于
findOneAndUpdate
和findByIdAndUpdate
,您还可以传递runValidators: true
选项来告诉mongoose运行验证器,但这只对包含在更新文档和only for some operations中的字段有效。因此,如果您对某个字段有约束,但您没有在更新文档中传递该字段,则mongoose将不执行任何验证。这可能会产生一些负面影响后果为了说明一个简单的模式,它将如下所示:
字符串
现在,如果您像这样执行
findOneAndUpdate
或findByIdAndUpdate
:型
然后,即使使用
runValidators
选项,也不会在veryImportantProperty
上进行验证,因为它不包含在req.body
中,所以mongoose将在没有它的情况下创建文档。即使您像这样使用
$set
运算符:型
如果没有
veryImportantProperty
,它仍然会保存新文档。使用Model.create()
,您给予更好的数据完整性,更容易调试,并且在创建操作失败时,您可以向用户发送更好的错误响应。这是一个简单的例子,但是对于更复杂的验证,事情可能会很快变得混乱,调试起来也会很困难,特别是在离开一段时间后重新访问代码库的时候。