How can I implement set/get/destroy methods in fastify-session to effectively save the session data in MongoDB?

I am working with TypeScript and trying to find a way to store sessions in mongoDB rather than in memory. After reading the documentation, I still couldn't figure it out (https://github.com/SerayaEryn/fastify-session). Can anyone guide me on how to achieve this?

Should I create a set method that accesses mongoDB to insert records with sessionId and also implement get and destroy methods? I have implemented them and they seem to be working fine. Is there anything wrong with my approach?

import fastifySession from 'fastify-session';
import mongoose from 'mongoose';
import Session from './schemas/sessionSchema';

// MongoDB connection setup
...

class Database {
    constructor() {
        this.connect();
        this.sessionStore = new SessionStore();
    }

    sessionStore: fastifySession.SessionStore;

    connect() {
        // Connecting to MongoDB
    }
}

class SessionStore implements fastifySession.SessionStore {

    // Methods for set, get, and destroy sessions in mongoDB
    ...

export default new Database();

// Defining schema and model for session data in mongoDB
...

export default session;
// Setting up fastify server with cookies and session management
...

app.get('/', async (req) => {
 return `hello`;
});

app.listen(PORT, (err, address) => {
    if (err) {
        console.error(err);
        process.exit(1);
    }

    console.log(`Server listening at ${address}`);
});

Answer №1

Have you considered utilizing the 'connect-mongodb' library? By incorporating the connect-mongo package into your code, you are able to configure the store option for fastify-session:

app.register(fastifySession, {
    cookieName: 'YOUR_SESSION_COOKIE_NAME',
    secret: 'YOUR_SESSION_SECRET',
    saveUninitialized: false,
    cookie: {
        path: '/',
        secure: process.env.NODE_ENV === 'production',
        maxAge: MAX_SESSION_AGE,
    },
    store: new MongoStore({
        mongoUrl: 'YOUR_MONGODB_URL',
    }),
});

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

When I select a checkbox in Angular 2, the checkall function does not continue to mark the selected checkbox

How can I check if a checkbox is already marked when the selectAll method is applied, and then continue marking it instead of toggling it? selectAll() { for (let i = 0; i < this.suppliersCheckbox.length; i++) { if (this.suppliersCheckbox[i].type == " ...

Merging two arrays into one, calculating the total sum of their attributes, all with the help of

I have data in two arrays retrieved from MongoDB and I am looking for a way to merge them seamlessly. Here are the arrays: a=[{country: 'de', count: 7},{country: 'es', count: 1}] b=[{country: 'de', count: 2}, {country: &apos ...

parsing a TypeScript query

Is there a simpler way to convert a query string into an object while preserving the respective data types? Let me provide some context: I utilize a table from an external service that generates filters as I add them. The challenge arises when I need to en ...

What are the reasons behind the inconsistency in matching function signatures by the TypeScript compiler?

Why doesn't the typescript compiler always match function signatures correctly, as shown in the examples below: type Func = (a: string, b: number)=>void //flagged as expected const func1: Func = true //not flagged as expected const func2: Func = ...

Setting up a connection between an Express server and a Mongoose database in

As someone who is relatively new to the express framework and mongoose database, I have mainly worked with relational databases in the past. I am attempting to create a database using the script below. Currently, mongod.exe is running and listening on loca ...

Use the useEffect hook to pass newly updated data to a FlatList component

I have encountered an issue with updating a FlatList component in my React Native application. The scenario involves running a graphql query to render items and then refetching the data when a mutation is executed using Apollo's refetch option. Althou ...

What is the most effective method for implementing an automated system for removing data from a mongoDB database?

My chat bot is currently set up to save records in MongoDB. The object stored in Mongo has a field called expiration_time which represents a number in minutes. { ..., expiration_time: 12451525, ... } Initially, I planned to use setInterval on the web app ...

Utilizing chrome.scripting to inject scripts in TypeScript

I am currently facing an issue wherein I am attempting to integrate chrome extension JavaScript code with TypeScript: const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); let result; try { [{ result }] = await c ...

mongo-express pod fails to launch correctly

I encountered an issue while trying to start the mongo-express pod in a k8s cluster. The error message was: "[MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Ser ...

Planting relational Mongo DB information within RAILS

As a newcomer to MonogoDB, I have successfully seeded data but am struggling with relational aspects. In my model, I include: has_and_belongs_to_many :users field: encrypted_password, type: String, default: "" field: name, type: String field: address, t ...

Having an issue with my Typescript code that is throwing a "Uncaught ReferenceError: angular is not defined" error

I am currently in the early stages of learning typescript with angularjs through online video tutorials. I have encountered an issue while attempting to include the angular module in my "app.ts" file, which serves as the main file in the backend. Below is ...

Can anyone provide guidance on updating a MongoDB collection with the stepzen schema?

After successfully figuring out the process of reading and creating a MongoDB collection entry using stepzen, I've hit a roadblock when it comes to updating an entry. I'm struggling to understand how to proceed with this. Below is what I think th ...

Heroku Application Dysfunction Limited to Local Machine

Experiencing a strange issue with my Heroku setup. I developed an application using React, JavaScript, Node, and Mongo. When I access the link to my app on my local machine: , I can see the website, but changes are not reflecting when pushed to Heroku. ...

Is there a way to efficiently convert JSON into a case class, especially when dealing with a field name that happens to be a

Currently in the world of Play Framework (2.6), I find myself automatically mapping JSON to case classes from MongoDB using ReactiveMongo 0.12 with JSON Collections. To test geospatial queries, I have imported a dataset into MongoDB as a collection from th ...

Saving transformed dates within MongoDB

While working on my first project, I realized that MongoDB stores dates in UTC. This caused issues with birthdates being stored at day X-1 23:00:00 instead of day X 00:00 as intended. I attempted to use moment.js to convert the date to my timezone before s ...

Update Multiple Rows Based on a Condition

Is there a method for updating multiple rows based on a specific condition using the Parse.com REST API? Consider a "Location" class with various locations. Each entry contains a "status" column that stores an enum string value such as "ok" or "error". I ...

Transform Promise<any> into a designated type failure

Beginner inquiry concerning typescript/angular4+/ionic4. I have a service set up to make backend REST calls, and based on the response received, I need to store that data in local storage for future reference. However, I am encountering a type conversion e ...

Utilizing custom i18n blocks for Vue 3 and Vuetify 3 to enhance locale messages

Looking to localize messages separately for each component? Check out this example for Vue 2. But how can it be done for Vue 3 and Vuetify 3? Here's what I've tried: package.json "dependencies": { "@mdi/font": "6.5 ...

Inquiring about the application of spread argument in TypeScript

Here is some code I'm working on: import _ from 'lodash'; function test(num1: number, num2: number) { console.log(num1, num2); } test(..._.take(_.shuffle([0, 1, 2]), 2)); I encountered a TS2556 error while using the TS playground and ...

Exploring the wonders of using the Async Pipe with Reactive Extensions

I'm facing a little issue with the async pipe in Angular. Here's my scenario: I need to execute nested observables using the async pipe in HTML because I'm utilizing the on-push change detection strategy and would like to avoid workarounds ...