【问题标题】:After submitting the form, user can still edit it. I want to enable the feature of timer that after 2 hours of submission提交表单后,用户仍然可以对其进行编辑。我想启用提交2小时后的计时器功能
【发布时间】:2020-08-04 22:40:26
【问题描述】:

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

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

【问题讨论】:

    标签: javascript jquery node.js mongodb handlebars.js


    【解决方案1】:

    为此,您可以创建一个具有用户 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()函数,例如在版本的post请求中。

    【讨论】:

    • 谢谢@ezeKG!最后我不希望文档在 2 小时后从数据库中删除。我只想为各个用户保留文档,因为他只是无法编辑它。意味着编辑选项将被永久锁定。需要做哪些改变?
    • 要删除的文档不是有用户信息的文档,只是带有用户ID的Editable。正如我所说,要实现它,您需要添加函数 isEditable() 作为中间件。我会用一个例子来编辑我的答案
    • 这是因为在 mongo 中,您无法在特定时间后更改属性。例如,不可能在两个小时后将布尔值从 true 更改为 false。
    • 非常感谢!也排在最后;路由器在“其他”条件下无法编辑后添加了该条件,而不是发送一些“不允许”,我希望这次仍然呈现同一页面以“查看”它。我将不得不制作两个单独的页面,一个用于“if”条件下的“EDIT”页面,另一个用于“其他”条件下的“VIEW”,我不想这样做。由于数据库会变得更重。我不能只在一页内实现吗?
    • @VikasYadav 我建议用两个不同的页面来做。但是,您可以通过使用像这样的一些 bool 值渲染来实现这一点:res.render('file', {edit: true}),然后,根据使用的模板,创建一个 if 语句。在车把中将是:{{if edit}} <!-- Edition Form --> {{else}} <-- View Data --> {{/if}}.
    猜你喜欢
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 2013-07-22
    • 2017-09-02
    • 1970-01-01
    相关资源
    最近更新 更多