Help needed with MongoDB!

My Schema looks like this (exact code here)

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    number:    {
        type: String,
        required: 'Number cannot be blank',
        unique: true,
    },
    messages: [
        {
            type: String
        }
    ],
    media: [
        {
            type: String
        }
    ],
    logs: [
        {
            type: String,
        }
    ]
});

const User = mongoose.model('User', userSchema);

module.exports=User;

I want to do these things below:

  • Make the logs expire after 24 hours
  • store the logs in the DB by the latest one which was created

Stack = Node + Express + MongoDB (using mongoose)

Comments (4)

Ilango's photo

Hello!

Make the logs expire after 24 hours

You have two options here:

  1. Create a cron job that will lookup documents in mongodb and delete them every 24 hours.
  2. The easier option, is to store logs in a separate collection. MongoDB allows you to set a TTL (Time To Live) for documents in a collection and automatically delete them when the time expires. Here's the documentation: docs.mongodb.com/manual/tutorial/expire-data

store the logs in the DB by the latest one which was created

I don't exactly understand what you want to accomplish here. Wouldn't a timestamp for each log work?

Show +1 replies
Ilango's photo

Instinct No. You can just add a timestamp field to each log and store it in MongoDB. When fetching it, you can just sort by timestamp: -1. So the logs returned from the query will be sorted by most recent first.

Instinct's photo

Ilango

Got it. Thanks a lot