我有一个mongoose模式,看起来如下所示:
const USERS_DATA = new Schema({
_id: Number,
name: String,
img: String,
date: Date,
phone: String,
article: String,
createdAt: {
type: Date,
required: true,
default: Date.now,
index: { expires: '3d' }
}
},
{
collection: "users",
_id: false,
}
);
我需要将数据推送到这个架构。
const User = mongoose.model("users", USERS_DATA);
function pushToDB() {
const newUser = new User({
name: INPUT.name,
img: INPUT.img,
date: INPUT.date,
phone: INPUT.phone,
article: INPUT.article,
});
newUser.save(function (err) {
mongoose.disconnect();
if (err) return console.log(err);
});
}
此数据推送到数据库后3天必须删除。如何在Node.js中实现?我发现它真的很混乱,试了很多代码。如有任何回答,我们将不胜感激!谢谢
附注。我使用mongoDb图集
您应该将将数据推入数据库的过程与在3天后将其删除的过程分开。您已经有了第一部分:)。对于第二部分,您可以编写一个函数deleteolddocument
。该函数将查询DB中创建时间为3天或更长的文档,并将其删除。然后,您可以定期运行该函数,例如每天运行一次。
伪代码,以备您需要:
async function deleteOldDocument() {
const 3DaysAgo = ...; // here you can subtract 3 days from now to obtain the value
// search for documents that are created from 3 days or more, using $lt operator
const documentToDelete = await User.find({"created_at" : {$lt : 3DaysAgo }});
// delete documents from database
.....
// recall the function after 1 days, you can change the frequence
setTimeOut(async function() {
await deleteOldDocument();
}), 86400);
}
// call deleteOldDocument to start the loop
deleteOldDocument();