Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

createIndex in mongoose

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.

like image 552
Middi Avatar asked Jul 15 '18 15:07

Middi


1 Answers

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 });
like image 193
Nandu Dharmapalan Avatar answered Sep 19 '22 14:09

Nandu Dharmapalan