【发布时间】:2020-08-04 22:40:26
【问题描述】:
我正在为我的项目使用 Nodejs、handlebar、jquery 和 mongodb/mongoosse 作为数据库。
提交表单后,用户仍然可以对其进行编辑。我想启用计时器功能,在提交 2 小时后用户无法编辑表单并被锁定。如何实现?
【问题讨论】:
标签: javascript jquery node.js mongodb handlebars.js
我正在为我的项目使用 Nodejs、handlebar、jquery 和 mongodb/mongoosse 作为数据库。
提交表单后,用户仍然可以对其进行编辑。我想启用计时器功能,在提交 2 小时后用户无法编辑表单并被锁定。如何实现?
【问题讨论】:
标签: javascript jquery node.js mongodb handlebars.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()函数,例如在版本的post请求中。
【讨论】:
res.render('file', {edit: true}),然后,根据使用的模板,创建一个 if 语句。在车把中将是:{{if edit}} <!-- Edition Form --> {{else}} <-- View Data --> {{/if}}.