Mongoose 过期未设置 - getIndexes 中未显示过期

问题描述

我有一个文档的有效期设置为 2 分钟。

const docSchema = new mongoose.Schema({
  createdAt: { type: Date,default: Date.Now },expireAt: { type: Date,default: Date.Now,index: { expires: "2m" } },});

const Doc = mongoose.model("Doc",docSchema);

创建 Doc 时(即 const doc = await Doc.create({});),我希望它设置过期时间。但是,有时是设置,有时不是。

我通过在 Mongo shell 中运行 Doc 来检查 db.docs.getIndexes() 是否过期。结果要么显示过期信息:

[
        ...{// some other object},// expiration info--->
        {
                "v" : 2,"key" : {
                        "expireAt" : 1
                },"name" : "expireAt_1","ns" : "expireDocument.docs","expireAfterSeconds" : 120,"background" : true
        }
]

或者它会遗漏它。我猜当它没有对文档应用到期时,它会忽略它。

它在设置和不设置时似乎有点随机。但是,我能够找出一个一致的情况,它在哪里设置,哪里没有设置,以便可以重新创建问题。不过,除了它们所处的顺序之外,我不知道是什么将这些情况分开了。

重新创建:

  1. 下载小型存储库 here。您还可以查看下面的 server.js 代码
  2. 在 VScode 中打开文件夹。
  3. CTR+` 打开终端。运行 npm i
  4. 点击调试器图标。在左上角播放 Expire Document 调试器。
  5. 脚本创建 Doc 后,调试器在 line 15 处暂停。暂停时,打开一个新终端。
  6. 运行 mongo 然后运行 ​​use expireDocument 以导航到正确的 数据库
  7. 运行 db.docs.getIndexes() 以查看索引。您将看到第二个对象包含有关`docs 预期的过期信息。
[
        {
                "v" : 2,"key" : {
                        "_id" : 1
                },"name" : "_id_","ns" : "expireDocument.docs"
        },// second object-->
        {
                "v" : 2,"background" : true
        }
]
  1. 运行 db.docs.drop()删除集合
  2. 取消暂停调试器。
  3. 同样,在脚本创建另一个 Doc 后,调试器将在 line 22 处暂停。当它暂停时再次运行 db.docs.getIndexes()。出于某种原因,这次不会有任何第二个对象表明有 expireAt 信息。
[
        {
                "v" : 2,"ns" : "expireDocument.docs"
        }
]

为什么?

为什么我没有设置一致的到期时间?

server.js 代码

const mongoose = require('mongoose');

const docSchema = new mongoose.Schema({
  createdAt: { type: Date,index: { expires: '2m' } },});

const Doc = mongoose.model('Doc',docSchema);

const run = async function () {
  // make document
  const doc1 = await Doc.create({});

  debugger;
  // While paused:
  // 1. run db.docs.getIndexes() in mongo shell and there will be a second object with "key":{ "expireAt":1}
  // 2. then run db.docs.drop() to drop the documents
  // 3. unpause script

  // make 2nd document
  const doc2 = await Doc.create({});
  debugger; // run db.docs.getIndexes() in mongo shell and if you dropped in step #2 when script was pause at line 14,there will be no second object with "key":{ "expireAt":1}
};
mongoose
  .connect('mongodb://localhost/expireDocument',{
    useNewUrlParser: true,useUnifiedTopology: true,useFindAndModify: true,})
  .then(() => console.log('Successfully connect to MongoDB.\n'))
  .catch((err) => console.error('Connection error',err));

run();

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)