我有一个express.js应用程序,允许用户发布行为。我想将这些帖子每天限制为一个。从服务器端开始,仅当当前用户尚未在同一天发布Act时,我才想更改发布路由。在当前路线(如下所示)中,我正在尝试将上午00:00的当前日期与用户的上一个法令的created_at日期进行比较。如果created_at> = start_of_current_date,则该帖子不会发生。但是,将记录created_at,但在条件中返回undefined。
这是我的路线:
// POST new Act route
router.post('/', auth.required, async (req, res, next) => {
const now = new Date();
// return last created Act
result = await Act
.query()
.where('users_id', req.user.id)
.orderBy('created_at', 'desc')
.limit(1);
console.log('this is the last act of user ', req.user.id, ': ', result);
console.log('this is the created_at last act of user ', req.user.id, ': ', result.created_at);
console.log('this is the start of today ', req.user.id, ': ', now.setHours(0,0,0,0));
// conditional to disable if last Act.created_at == Today
if(result.created_at >= now.setHours(0,0,0,0)) {
return Act.query()
.insert({
deed: req.body.act.deed,
users_id: req.body.act.userId
})
.then( function () {
res.json({ success: true, message: 'ok' }); // respond back to request
})
} else {
res.json ({
"message": "This user already acted today."
});
}
});
这是控制台中的结果,包括我的控制台日志:
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Running on localhost:8000
this is the last act of user 1 : [ Act {
id: 6,
deed: 'Writing',
users_id: 1,
created_at: 2019-09-23T20:04:28.393Z,
updated_at: 2019-09-23T20:04:28.393Z } ]
this is the created_at last act of user 1 : undefined
this is the start of today 1 : 1569902400000
更新:结果返回一个数组,因此使用result [0],我可以获取一个值。 h / e,需要转换输出以将其与当前日期进行比较。这是当前输出:
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Running on localhost:8000
this is the last act of user 1 : [ Act {
id: 6,
deed: 'Writing',
users_id: 1,
created_at: 2019-09-23T20:04:28.393Z,
updated_at: 2019-09-23T20:04:28.393Z } ]
this is the date of the last act of user 1 : 2019-09-23T20:04:28.393Z
this is the start of today 1 : 1569902400000
这可以使用getTime()帮助程序:
// POST new act route
router.post('/', auth.required, async (req, res, next) => {
const now = new Date();
// return last created Act
result = await Act
.query()
.where('users_id', req.user.id)
.orderBy('created_at', 'desc')
.limit(1);
console.log('this is the last act of user ', req.user.id, ': ', result);
console.log('this is the date of the last act of user ', req.user.id, ': ', result[0].created_at.getTime());
console.log('this is the start of today ', req.user.id, ': ', now.setHours(0,0,0,0));
// conditional to disable if last Act.created_at == Today
if(result[0].created_at.getTime() <= now.setHours(0,0,0,0)) {
return Act.query()
.insert({
deed: req.body.act.deed,
users_id: req.body.act.userId
})
.then( function () {
res.json({ success: true, message: 'ok' }); // respond back to request
})
} else {
res.json ({
"message": "This user already acted today."
});
}
});