如果索引已存在于 MongoDB,则 mongoose 模式中的过期设置将被忽略
Expires setting in mongoose schema is ignored if index already exists at MongoDB
我在 mongoose 模式中使用 expires
字段来设置给定字段的过期时间。例如:
var Crumbs = new Schema({
...
timestamp: {
type: Date,
expires: 3600,
required: true
},
...
});
效果是预期的,并且在 MongoDB 处创建了以下索引 如果该索引以前不存在:
> db.crumbs.getIndexes()
[
...
{
"v" : 2,
"key" : {
"timestamp" : 1
},
"name" : "timestamp_1",
"ns" : "mydb.crumbs",
"expireAfterSeconds" : 36000,
"background" : true
}
]
但是,如果索引以前存在,则不会创建它。例如,如果我在我的代码中更改为 expires: 360
并且我重新 运行 我的程序, MongoDB 处的 "expireAfterSeconds"
保持为 36000
.
有没有办法强制索引使用架构中定义的值,即使索引已经存在?
你不能从模式定义中做到这一点。
最好的方法是直接在数据库中删除索引。
或者,将其从脚本中删除。例如
mongoose.connections[0].collections("collectionname")
.dropIndex("propertyName",callback)
感谢Alex Blex的提示,我终于解决了这个问题。首先删除索引,然后使用新的过期值重新创建:
mongoose.connections[0].collections.crumbs.dropIndex({timestamp: 1}, function (error) {
if (error) {
// This happens typically if the index doesn't exist but it doesn't hurt anyway
}
mongoose.connections[0].collections.crumbs.ensureIndex({timestamp: 1}, {expireAfterSeconds: 360});
});
我在 mongoose 模式中使用 expires
字段来设置给定字段的过期时间。例如:
var Crumbs = new Schema({
...
timestamp: {
type: Date,
expires: 3600,
required: true
},
...
});
效果是预期的,并且在 MongoDB 处创建了以下索引 如果该索引以前不存在:
> db.crumbs.getIndexes()
[
...
{
"v" : 2,
"key" : {
"timestamp" : 1
},
"name" : "timestamp_1",
"ns" : "mydb.crumbs",
"expireAfterSeconds" : 36000,
"background" : true
}
]
但是,如果索引以前存在,则不会创建它。例如,如果我在我的代码中更改为 expires: 360
并且我重新 运行 我的程序, MongoDB 处的 "expireAfterSeconds"
保持为 36000
.
有没有办法强制索引使用架构中定义的值,即使索引已经存在?
你不能从模式定义中做到这一点。
最好的方法是直接在数据库中删除索引。
或者,将其从脚本中删除。例如
mongoose.connections[0].collections("collectionname")
.dropIndex("propertyName",callback)
感谢Alex Blex的提示,我终于解决了这个问题。首先删除索引,然后使用新的过期值重新创建:
mongoose.connections[0].collections.crumbs.dropIndex({timestamp: 1}, function (error) {
if (error) {
// This happens typically if the index doesn't exist but it doesn't hurt anyway
}
mongoose.connections[0].collections.crumbs.ensureIndex({timestamp: 1}, {expireAfterSeconds: 360});
});