What is the best way to update a field within a MongoDB document based on a specified duration?

In the process of creating a new application with JS, Node.JS, Express, and MongoDB, I am implementing a feature where users can purchase listings. These listings are stored as documents in a MongoDB database. My goal is to have the listings automatically "expire" after a specific period of time, such as 30 days. One approach I am considering is adding a boolean field named "expired" to the document that starts as false but switches to true once the expiration time elapses. Is there a way to use JavaScript to associate a timer with each listing and then update the database accordingly when the timer runs out?

Answer №1

To automatically delete documents after a specific time, you need to implement a TTL index. This Time To Live index will manage when the document should be removed from the database.

Here is an example of how to create a TTL index:

user.createIndexes({ "createdAt": 1 }, { expireAfterSeconds: 86400 })

In this case, 'user' represents the schema and 'createdAt' specifies the field that determines when the document will expire.

You have the option to create the index either through the nodejs driver or directly in the mongo shell for the collection.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate Angular frontend into current website or project

I've successfully built a website using bootstrap, but now I'm looking to integrate Angular in order to transform it into a single page application. The goal is that when a user clicks on a link, only the necessary content will be loaded from the ...

Creating a visual representation of data using Google Charts to display a stacked bar chart

I wrote a script to display a stacked Google chart using JSON data stored on the wwwroot directory - <html> <head> <title>DevOps Monitoring Application</title> <link rel="icon" type="image/png" hr ...

While troubleshooting the app, I encountered an error that says: "The property 'answers' cannot be read as it is undefined."

Everything was going smoothly with my app until it suddenly crashed, displaying the error message "Cannot read property 'answers' of undefined". Let's take a look at the specific piece of code causing the issue: function mapStateToProps({ ...

Sending files using AJAX without FormData in Internet Explorer 9

Unfortunately, IE9 does not support FormData, making file uploads via XMLHttpRequest a more challenging task. Is there a workaround for this issue? I've come across mentions of using iFrames, but the process seems complex and unclear on how to transf ...

In jQuery, conditionally nest divs within another div based on a specific requirement

There is a container with multiple nested elements that need to be rearranged based on the value of their custom attribute. The goal is to reorder those elements at the end of the container if their 'data-keep-down' attribute is set to true, usin ...

Can a JavaScript function be sent back via AJAX from PHP?

Can a javascript function be returned via Ajax from php? Typically, I would just return a value and handle it in plain javascript. However, since I am working on an Apache Cordova mobile app, I need to approach things differently. account = localStorage.g ...

"AngularJS directive mandating the use of the required attribute for internal control

I've encountered a challenge with this specific issue. We are using a directive called deeplink, which contains the following code: restrict: 'E', require: 'ngModel', scope: { smDropdown: '=smDeeplinkDropdown', s ...

What is the process of connecting marionette rendered views to the DOM?

I am encountering a challenge with my simple setup using Marionette that I am trying to resolve. My issue lies within a view containing a collection: var MyItemsView = Marionette.View.extend({ template: "#some-template" }); var view = new MyItemsVie ...

Material-ui does not adjust Typography color based on the theme selected

Exploring material-ui, I have implemented two themes: const darkTheme = createMuiTheme({ palette: { type: "dark" } }); const lightTheme = createMuiTheme({ palette: { type: "light" } }); However, when utilizing the Typography component, t ...

"Enhancing user interaction with Vue.js through the stunning ripple effect on

Is there a way to customize the ripple effect from this source so that it doesn't always have to be a DIV? Here's an example: Currently, when I implement it like this: <ripple class="btn">send</ripple> It works as expected, but as ...

Client event triggered twice by server

Hey there! I'm currently working on creating a simple chat app using socket.io and express. One issue I'm facing is that when a user sends a message, the server broadcasts it to the rest of the clients, but it seems to be happening twice. I can& ...

What led the Typescript Team to decide against making === the default option?

Given that Typescript is known for its type safety, it can seem odd that the == operator still exists. Is there a specific rationale behind this decision? ...

In JS/JSON, a new line of data is generated every hour

Recently, I have been experimenting with DiscordJS and exploring its logging functionality. I am aware that the method I am using is outdated and may not be the most secure for actively changing data, but I am intrigued. let count = JSON.parse(fs.readFile ...

Exploring elementary Expressjs query concepts

Just getting started with nodejs and feeling a bit confused. I have a form on my website where users can submit information, and I want to display a response message in an HTML element once the form is submitted. I've been using body parser and Jade v ...

Using Angular 8.x for routing with customized outlet names

I am attempting to set up routing in my Angular 8.x application, utilizing lazy loading and named outlets. Here is the current configuration: main-layout.html <header> <app-top-menu></app-top-menu> </header> <mat-sidenav-cont ...

Expanding and Shrinking Text Areas with Jquery

I am looking to create a textarea that comes preloaded with content. The height of the textarea should adjust to auto when there is content present, but switch to a height of 4.2rem when it is empty. Additionally, I want the textarea to dynamically increas ...

Is there any way to remove the two default aspNetHidden Divs in asp.net web forms?

After creating an empty webform page in asp.net, the generated code looks like this: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Threetier.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org ...

"Encountering issues with getStaticPaths not generating any paths

I have a folder named data which contains a file called events.ts: export const EventsData: Event[] = [ { name: 'School-Uniform-Distribution', images: ['/community/conferences/react-foo.png', "/community/conferences/react ...

Is the functionality of defineProperty for elements malfunctioning on iOS6?

There seems to be an issue with JavaScript's defineProperty and __defineSetter not working on elements in iOS6. It functions correctly on all other browsers and earlier versions of iOS. Does anyone have more information on this? <input id='Bu ...

Trouble with React Native ListView Item Visibility

I'm currently working on integrating the React Native <ListView /> component with the <List /> and <ListItem /> components from React Native Elements. However, I seem to be facing an issue where the <ListItem /> component is no ...