记录一下学习过程中遇到的问题,百度到很多文章发现都没有node的或者是有各种问题例如数据在1分钟内就删除了
解决:
// tokendb.js
const mongoose = require("mongoose");
//net start mongodb
var moment = require('moment');
mongoose.connect("mongodb://localhost/picsdb", { useNewUrlParser: true, useUnifiedTopology: true })
.catch((error) => console.log(error));
const tokendbSchema = new mongoose.Schema({
tokenid: {
type: String,
},
createAt: {
type: Date,
}
})
const tokendb = mongoose.model('tokendb', tokendbSchema);
console.log(tokendbSchema.index)
//下面的代码是设置过期时间的关键代码,上面的createAt必须是Date类型
tokendb.createIndexes(tokendbSchema.index({ createAt:new moment().valueOf()}, { expireAfterSeconds: 0}), function (err, info) {})
module.exports.tokendb = tokendb
//路由 index.js
tokendb.create({
tokenid: token,
createAt:moment().add(120, 'minutes').toDate(),//120分钟后过期,实际上可能有十几秒的延迟
})