提交表单后,用户仍然可以对其进行编辑。我想在提交 2 小时后启用计时器功能

After submitting the form, user can still edit it. I want to enable the feature of timer that after 2 hours of submission

我正在为我的项目使用 Nodejs、handlebar、jquery 和 mongodb/mongoosse 作为数据库。

提交表单后,用户仍然可以对其进行编辑。我想启用计时器的一项功能,即在提交 2 小时后用户无法编辑表单并被锁定。如何实现?

为此,您可以创建一个具有用户 ID(只是它)的新架构,然后使用过期 属性。所以它会是这样的:

const editable = new mongoose.Schema({
  userId: String,
  createdAt: {type: Date, default: Date.now(), expires: 3600*2}
});
const Editable = mongoose.model('Editable', editable)

现在,当您保存新用户时,异步创建可编辑对象:

const user = new User(data)
user.save().then(async(userData) => {
  const editable = new Editable({userId: userData.id})
  await editable.save()
})

然后您需要创建一个中间件函数来检查文档是否确实存在。可能是这样的:

function isEditable(userId){
  Editable.countDocuments({userId : userId}, function (err, data) {
    if (data > 0){
      return true
    }else{
      return false
    }
  });
}

在这个例子中,用户将有两个小时的时间来编辑表单,因为在两个小时后,具有他的 ID 的文档将被删除,并且 isEditable() 函数将 return false。

当用户尝试编辑表单时,您可以像这样实现功能:

router.get('/edit-form/:id', function(req, res, next){
  const user_id = req.params.id // This is an example of the get router to the edition form which takes the user id as a parameter

  if(isEditable(user_id)){ //Implementation of the function above
    //Render the form so the user can change it
  }else{
    res.status(403).send("Not allowed") //Status forbidden with a message
  }
})

这只是一个例子,你可以在你想要的地方实现isEditable()函数,比如在版本的post请求中。