设置过期后的字段(MongoDB)



我有一个小的数据库结构:

export const ApplicationSchema = new Schema({
ownerId: String,
ownerName: String,
region: String,
fromAddress: String,
phone: String,
cameAddress: String,
status: {
type: String,
enum: ['new', 'booked', 'completed'],
default: 'new'
},
})

我需要更改"状态",24 小时后,状态应等于"已预订",该怎么做?

MongoDB有一个名为Scheduled Triggers的工具,它可以让你这样做: https://docs.mongodb.com/stitch/triggers/scheduled-triggers/

但是,对于您的问题来说,这将是一个复杂而繁重的解决方案。您可以使用"createdAt"字段并为您的当前状态提供一个虚拟字段来执行某些操作:

export const ApplicationSchema = new Schema({
ownerId: String,
ownerName: String,
region: String,
fromAddress: String,
phone: String,
cameAddress: String,
createdAt: Date,
status: {
type: String,
enum: ['new', 'booked', 'completed'],
default: 'new'
},
toJSON: { virtuals: true }
})
ApplicationSchema.virtual('status.current')
.get(function () {
// subtracting and checking if it's been a day in milliseconds
if ((Date.now() - +new Date(this.createdAt)) >= 86400000) {
return 'completed'
}
return this.status
})

您必须使用 status.current 而不是 status 来检查您的状态。 查看此处(https://mongoosejs.com/docs/2.7.x/docs/virtuals.html(以了解有关虚拟字段的更多信息。

我认为你不能单独使用MongoDB来做到这一点。
在我的项目中,我正在使用这个 npm 包:
https://www.npmjs.com/package/cron

这使您可以定期运行任务。就像Linux系统上的Cron作业一样,但这个包不依赖于Linux Cron。

最新更新