首页 > 解决方案 > 在再次刷新后保存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 });
});
});
});

标签: node.jsmongodbmongoose

解决方案


这是预期的行为。每当您调用save它时,它都会创建一个新文档。如果要限制创建同一文档两次或多次,则需要在调用之前检查该文档是否已存在save。有两种方法可以防止创建具有相同数据的文档:

  1. 您必须使用 . 检查文档findOne。如果文档存在则不调用save,如果不存在则插入新文档。

  2. 在进行唯一组合的字段上定义唯一复合索引,以免插入具有相同数据的文档。

可以从这里获取参考:Unique Compound Index


推荐阅读