Node.js TTL Not working to expire data

632 views Asked by At

Please help, i`m using node.js and mongodb i want to use TTL (Time TO Live) to expire the collection on my database but it does not work and error will show : TypeError: Cannot read property 'createIndex' of undefined and here is my code: thank in advance

var MongoClient = require('mongodb').MongoClient;
var mongodbURI = 'mongodb://localhost:27017/ex1';
var startDate = new Date();

MongoClient.connect(mongodbURI,setupCollection);

function setupCollection(err, db) {
if(!err) {
console.log("We are connected");
collection=db.collection("test1");
db.test1.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 300 } )

        }
 }
1

There are 1 answers

0
Max Koretskyi On BEST ANSWER

This syntax

db.test1

to obtain a collection is supported by mongo shell, but when using node.js driver you have to obtain collection like this:

db.collection("test1")

so in your case it's like this:

db.collection("test1").createIndex( { "createdAt": 1 }, { expireAfterSeconds: 300 } )

Here is the relevant docs.