I am trying to make an exclusive lock semaphore using mongoose on a documentDb collection document. The index and document gets created alright, however the document never expire. I've tried turning createdAt into a string and set it to an ISO string, to no avail. Any ideas how to get ttl to work in documentDb 4.0? I can delete the document when I am done, however I want to automatically clear this in case the executed script dies holding the lock.
const mongoose = require('mongoose');
const {Schema} = require("mongoose");
const { v4: uuidv4 } = require('uuid');
const { exec } = require("child_process");
const whoAmI = uuidv4();
(async () => {
await mongoose.connect(connectionString);
const LockSchema = new Schema({
id: String,
owner: String,
createdAt: { type: Date, required: true, default: Date.now },
});
LockSchema.index( { "createdAt": 1 }, { expireAfterSeconds: 30 } )
const Lock = mongoose.model("migration", LockSchema, "locks");
result = await Lock.findOneAndUpdate({id: "lock"}, { $setOnInsert: { owner: whoAmI}}, { upsert: true, new: true}).lean();
if (result?.owner === whoAmI) {
await exec("<something>", async (error, stdout, stderr) => {
mongoose.disconnect();
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log("done...")
});
}
})();
TTL Index property currently is not available to DocDB Elastic Cluster.
Check the DocDB type you are using to be sure that isn't the problem. I was using DocDB 5.0 but it was the Elastic version, this could have saved me a lot of time.
You can check the docs with the available features here:
Command | 3.6 | 4.0 | 5.0 | Elastic cluster |
---|---|---|---|---|
TTL | Yes | Yes | Yes | No |
Unique | Yes | Yes | Yes | Yes |
Partial | No | No | No | No |
Case Insensitive | No | No | No | No |
Sparse | Yes | Yes | Yes | No |
Background | Yes | Yes | Yes | No |