首页 > 解决方案 > 提交表单后,用户仍然可以对其进行编辑。我想启用提交2小时后的计时器功能

问题描述

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

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

标签: javascriptjquerynode.jsmongodbhandlebars.js

解决方案


为此,您可以创建一个具有用户 ID(仅此而已)的新模式,然后使用 expires 属性。所以它会是这样的:

const editable = new mongoose.Schema({
  userId: String,
  createdAt: {type: Date, default: Date.now(), expires: 3600*2}
});
const Editable = mongoose.model('Editable', 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()函数将返回 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() 函数,例如在版本的发布请求中。


推荐阅读