node.js - 在再次刷新后保存mongoDB数据时保存相同的数据
问题描述
我正在学习 mongodb 和 Mongoose。我建立了一个员工详细记录,我的代码正在运行。但是有一个问题,因为我再次刷新页面它提交以前的数据。我该如何解决这个错误。
router.post("/", function (req, res, next) {
const empData = req.body;
const postData = new empDetails({
name: empData.name,
age: empData.age,
department: empData.department,
email: empData.email,
present: empData.present,
empType: empData.type,
rate: empData.rate,
hours: empData.hours,
total: parseInt(empData.rate) * parseInt(empData.hours),
});
postData.save(function (err, res1) {
if (err) throw err;
employeeDetails.exec(function (err, data) {
if (err) throw err;
res.render("employee", { title: "Employee Details", records: data });
});
});
});
解决方案
这是预期的行为。每当您调用save
它时,它都会创建一个新文档。如果要限制创建同一文档两次或多次,则需要在调用之前检查该文档是否已存在save
。有两种方法可以防止创建具有相同数据的文档:
您必须使用 . 检查文档
findOne
。如果文档存在则不调用save
,如果不存在则插入新文档。在进行唯一组合的字段上定义唯一复合索引,以免插入具有相同数据的文档。
可以从这里获取参考:Unique Compound Index
推荐阅读
- python - pickle.loads 给出“模块”对象没有属性“
' 在 Pyspark Pandas Udf 中 - kotlin - 为什么不能在 let 或 run 中使用 continue
- asp.net - 如何存储一个
- arrays - Swift MacOS 更改整个应用程序的数组值
- ios - 如何允许在 UITextVIew 上显示所有阿拉伯字符?
- python - 将 Python 中的 .txt 文件解析为 Numpy 数组
- python - 你能告诉我 Caffe 模型中的 deploy.prototxt 是做什么用的吗?
- php - PHP memcached 如何确定集群中的哪个节点存储密钥?
- azure - 从自定义视觉导出标签
- javascript - 黑框而不是画布中的图像