Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

MongoDB documents expiring too soon (mongoose)

I set expiry time to 24 hours, but the documents expire after around 5-10 minutes (I haven't timed it exactly). What am I doing wrong? My schema:

const collectionSchema = new mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User"
  },
  name: {
    type: String,
    maxLength: 30,
    required: true
  },
  entries: [{ type: mongoose.Schema.Types.ObjectId, ref: "Entry" }],
  expireAt: { type: Date, expires: 60 * 60 * 24 }
});

In the post route, I conditionally set the date so that inlogged clients get data persistence.

router.post("/", auth, async (req, res) => {
  let date = null;
  if (!req.user) {
    date = new Date();
  }
  try {
    const collection = {
      userId: req.body.userId,
      name: req.body.name,
      expireAt: date
    };
    const newCollection = await Collection.create(collection);
    res.send(newCollection);
  } catch (error) {
    res.send(error.message);
  }
});

I thought I had a time-zone problem, but when I check the time stamp in MongoDB compass, it matches my time-zone. What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
by (100 points)
I'm having the same exact issue. Did you ever find a solution?
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I tested this:

var TestSchema = new Schema({
  name: String,
  createdAt: { type: Date, expires: '2m', default: Date.now }
});

Documents ware deleted after the second minute and I also confirmed that the TTL index was properly created (as a background one by default) with TTL of 120 seconds.

Try that time format and see if that works for you.

Also note that any expected changes to the index via your mongo schema would not be reflected until you manually remove the previous index and start your app to auto-create the new one.

MongoDB version: 3.6.5


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...