正好1小时后,我需要删除购物车下数组中的项目。
我做了一些研究,但我尝试的方法对我不起作用。
const userSchema = mongoose.Schema({
email: {
type: String,
validate: [isEmail, 'Geçersiz mail adresi!'],
},
password: {
type: String,
required: true
},
resetToken: String,
resetTokenExpiration: Date,
isAdmin: {
type: Boolean,
default: false
},
cart: {
items: [{
productId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
required: true
},
quantity: {
type: Number,
required: true
}
}]
}
});
您想要更新部分数据,这必须是自动的。我确定您不会删除用户详细信息,只想使用
cart
或 []
更新 null
数据。
出于此类目的,您可以使用 node.js 上的 cron-jobs,该任务每小时触发一次,但它会在指定时间删除所有文档,这可能会导致刚刚在购物车中添加商品的用户出现意外行为
1 minute
在 cron 作业运行之前。
但是,您可以进行查询来检查特定购物车是否过期,并且可以使用 cron-jobs 运行该查询,但我相信您需要解析每个文档,这可能会增加数据库的复杂性和不必要的负担。
因此,我建议您创建另一个集合来保存用户购物车信息,并将“ttl”添加到集合中作为密钥
createdAt
(随意命名),这是由 Mongodb
提供的,它将在特定文档的特定时间过后删除该文档。
为购物车特定集合创建索引
db.collectionName.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )
插入文档时:
db.log_events.insert( {
"createdAt": new Date(),
"logEvent": 2,
"logMessage": "Success!"
} )
为了彻底理解它,我建议您阅读this。
我不确定其他选项,但您可以使用类似 node-schedule 的东西,以一定的时间间隔运行并清理购物车数组。
为此,您需要在数据库中有一个额外的字段,它表示到期时间,即(购物车创建时间 + 1 小时)。此节点计划函数将检查字段值中的到期时间,如果该值大于当前时间,则将删除,否则将保持原样。
尝试议程
维护购物车的单独集合会有所帮助。
const userSchema = new mongoose.Schema({
email: {
type: String,
validate: [isEmail, 'Geçersiz mail adresi!'],
},
password: {
type: String,
required: true
},
resetToken: String,
resetTokenExpiration: Date,
isAdmin: {
type: Boolean,
default: false
},
cart: {
items: [{
productId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
required: true
},
quantity: {
type: Number,
required: true
}
}]
},
expiresAt: { type: Date, default: () => new Date(Date.now()+60*60*1000), },
});