为 MongoDB 集合设置过期 TTL
Setting expiration TTL on MongoDB collection
如何使用带有 mongoDB 集合的 Typeorm 设置 ttl 过期时间?我想自动删除记录,用猫鼬很容易做到这一点,但我不知道如何使用 TypeOrm 完成它。
在猫鼬中是这样完成的
const Schema = mongoose.Schema;
const YourSchema = new Schema({
expireAt: {
type: Date,
default: Date.now() + 10 * 60 * 1000 // expires in 10 minutes
},
});
这是我尝试过的实体代码,但因未知错误而失败。
import { Column, CreateDateColumn, Entity, Index, IndexOptions, ObjectID, ObjectIdColumn, Repository, UpdateDateColumn, getConnection } from 'typeorm'
import uuid from 'node-uuid'
const indexOpts: IndexOptions = {
expireAfterSeconds: 10 * 60 * 60, // expires in 10 minutes,
}
@Entity()
export class RefreshToken {
@Index(indexOpts)
@ObjectIdColumn()
public id!: ObjectID
@CreateDateColumn()
public createdAt!: string
@UpdateDateColumn()
public updatedAt!: string
@Column()
public userId!: string
@Column()
public token: string = uuid.v4()
}
更新感谢@Jijo_Alexander 我添加了以下内容
export const getRefreshTokenModelRepo = async (): Promise<MongoRepository<RefreshToken>> => {
const repo = getMongoRepository(RefreshToken)
const expireAfterSeconds = 600 // 60 * 60 * 24 * 30
await repo.createCollectionIndex('refreshTokenExpireIndex', { expireAfterSeconds })
return repo
}
但是添加的记录不会自动删除。所以也许我遗漏了索引在 mongodb
中的工作方式
你可以试试createCollectionIndex
getConnection.createCollectionIndex(RefreshToken, "public", { expireAfterSeconds: 600 }); // expires in 10 minutes
- 索引字段必须是 BSON 日期类型或 BSON 日期数组
- 如果文档中的索引字段不是日期或包含日期值的数组,则文档不会过期。
- 如果文档不包含索引字段,则文档不会过期。
如何使用带有 mongoDB 集合的 Typeorm 设置 ttl 过期时间?我想自动删除记录,用猫鼬很容易做到这一点,但我不知道如何使用 TypeOrm 完成它。
在猫鼬中是这样完成的
const Schema = mongoose.Schema;
const YourSchema = new Schema({
expireAt: {
type: Date,
default: Date.now() + 10 * 60 * 1000 // expires in 10 minutes
},
});
这是我尝试过的实体代码,但因未知错误而失败。
import { Column, CreateDateColumn, Entity, Index, IndexOptions, ObjectID, ObjectIdColumn, Repository, UpdateDateColumn, getConnection } from 'typeorm'
import uuid from 'node-uuid'
const indexOpts: IndexOptions = {
expireAfterSeconds: 10 * 60 * 60, // expires in 10 minutes,
}
@Entity()
export class RefreshToken {
@Index(indexOpts)
@ObjectIdColumn()
public id!: ObjectID
@CreateDateColumn()
public createdAt!: string
@UpdateDateColumn()
public updatedAt!: string
@Column()
public userId!: string
@Column()
public token: string = uuid.v4()
}
更新感谢@Jijo_Alexander 我添加了以下内容
export const getRefreshTokenModelRepo = async (): Promise<MongoRepository<RefreshToken>> => {
const repo = getMongoRepository(RefreshToken)
const expireAfterSeconds = 600 // 60 * 60 * 24 * 30
await repo.createCollectionIndex('refreshTokenExpireIndex', { expireAfterSeconds })
return repo
}
但是添加的记录不会自动删除。所以也许我遗漏了索引在 mongodb
中的工作方式你可以试试createCollectionIndex
getConnection.createCollectionIndex(RefreshToken, "public", { expireAfterSeconds: 600 }); // expires in 10 minutes
- 索引字段必须是 BSON 日期类型或 BSON 日期数组
- 如果文档中的索引字段不是日期或包含日期值的数组,则文档不会过期。
- 如果文档不包含索引字段,则文档不会过期。