How do I remove items from my mongo database after an hour?
I've seen
db.Item.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 3600 })
thrown around but how do i implement that in nodejs?
my db entries look like this
{
"_id": {
"$oid": "5b4b64bc8c6e8add083431a3"
},
"location": {
"lat": 59.924209956924315,
"lng": 10.70636168616943
},
"name": "Richard Middleton",
"address": "Espresso House",
"message": "sdsd",
"createdAt": {
"$date": "2018-07-15T15:14:04.573Z"
},
"updatedAt": {
"$date": "2018-07-15T15:14:04.573Z"
},
I tried running it before my db.Item.find() for my get request but no luck.
Two ways to create index. First
const Schema = mongoose.Schema;
let user = new Schema({
email: {
type: String,
required: true,
index: true //---Index----
});
module.exports = mongoose.model('User', user);
Second method
const Schema = mongoose.Schema;
let user = new Schema({
email: {
type: String,
required: true
});
user.index({ email: 1 }); //---Index----
module.exports = mongoose.model('User', user);
When doing this if you are getting a warning(I am using MongoDB: 4.2.8 and Mongoose: 5.9.20)
DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
Then you might need to add 'useCreateIndex: true' to your mongoose.connect
mongoose.connect(Uri, { useNewUrlParser: true, useUnifiedTopology: true,
useCreateIndex: true });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With