Why am I unable to insert data into the 'sessions' database using connect-mongo?

I am utilizing connect-mongo in conjunction with express-session, and the session data is successfully being stored in Mongo.

However, I want to enhance the sessions collection utilized by connect-mongo in order to include my own fields on top of it.

I have created my custom sessions models in a file named sessions.js as shown below:

const mongoose = require('mongoose');

const SessionSchema = new mongoose.Schema({
    _id: {},
    session: {},
    expires: {},
    myNewVariable: {}
});

const Sessions = mongoose.model('sessions', SessionSchema);

module.exports = {Sessions};

In my server file, I have included the following:

const session = require('express-session');
const {mongoose} = require('./db/mongoose.js');
const {Sessions} = require('./models/sessions.js');
const MongoStore = require('connect-mongo')(session);

app.use(session({
  secret: SECRET,
  resave: true,
  saveUninitialized: true,
  store: new MongoStore({ mongooseConnection: mongoose.connection })
}));

app.post('/myRoute', function(req, res, next) {
      Sessions.findOneAndUpdate(
        {_id: req.session.id},
        {$set:{myNewVariable: myNewValue}},
        {new: true}).then((session) => {

            console.log('session: ' + JSON.stringify(session)); // displays correctly!

            // Perform operations with the session
      }).catch((e) => console.log('Something went wrong: %s', e));
});

The surprising part is that the print statement above shows the updated session object. However, upon inspecting the database later, the documents remain unchanged.

Attempting to create a completely different SessionsAlternative collection yielded successful updates. While this could be a workaround, it does not align with the intended concept of consolidating all data into a single sessions collection.

Is there a way to achieve this, and if so, what steps am I missing?

Answer №1

What is the reasoning behind not saving directly to session?

req.session.myNewVariable = "abc";

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

Combining react-md with material-ui components: A step-by-step guide

Is it possible to combine react-md and material-ui components together? I am attempting to utilize components from both libraries, however they seem to conflict with each other's styles. Do you have any suggestions or solutions? ...

Transforming a string that represents an array into an actual array using JavaScript

Currently, I am working on a project that involves the use of MySQL, React, and Express.js. One issue I have encountered is the need to save an array into MySQL. However, there seems to be no direct way to do this, so I had to convert the array into a st ...

Error: The specified element to insert before is not a direct descendant of this parent node

As I work on converting a jquery dragable script to plain javascript, I encountered an issue at the insertBefore point. The error message that pops up is: NotFoundError: Node.insertBefore: Child to insert before is not a child of this node. This particula ...

Guide to implementing CRUD operations on a remote MongoDB using Node.js

Recently, I delved into the world of NodeJS and discovered its server-side capabilities. My current project involves interacting with MongoDB on a remote server using the nodejs mongodb driver. With just a few lines of code, I am able to connect to the dat ...

What could be causing my for loop to become unresponsive?

My for loop seems to be populating all fields with the last object parsed. http://codepen.io/anon/pen/EKxNaN This is my current code. I created something similar on CodePen since I can't access JSON from the original source there. var championMaste ...

angular does not update dynamically created dropdowns with populated arrays

Upon loading the page, my initial dropdown functions correctly. However, the child dropdown is loaded from localstorage after the first dropdown. The issue arises when I load the second dropdown and set it to the default value - at this point, I am unabl ...

What is the best way to redirect to a specific page when logging out of a website?

To begin, let me outline the situation at hand. We have two distinct websites - website-A and website-B. Each of these websites is hosted on separate domains. A user has the ability to log in to website-B's homepage through the login page of webs ...

What is the best way to insert hyperlinks within every cell of a table using Angular?

I am currently working on a table created with ng-repeat in Angular. The cells are populated by variables in the scope. <tbody> <tr ng-repeat="item in items" myDirective> <td>{{item.title}}</td> <td>{{item.field}}&l ...

"Troubleshooting the Issue: Challenges with NodeJS, MongoDB, and Ajax for Uploading Multiple Files and Saving

I am currently working on implementing Ajax multiple PDF uploads to a NodeJS server and storing the file paths in MongoDB within the Book Document. One issue that I am facing is that when I attempt to upload multiple files for the first time, only one boo ...

Modifying Selectize Ajax data in real-time

How can the student_id be changed each time the modal is opened? This is the code: $('#relationshipModal input[name=existing_user]').selectize({ valueField: 'id', searchField: 'name', options: [], create: fal ...

Looking for a custom textured circle in three.js?

Is there a way to create a circle with a texture on one side in three.js without using sprites? I was considering using THREE.CylinderGeometry, but I'm unsure of where to add the "materials" in the new THREE.CylinderGeometry(...) section. Any suggest ...

Could the absence of an external style sheet for CSS be hindering the execution of my code?

A generous Stack Overflow user provided me with the code you see here and their JSFiddle can be accessed at http://jsfiddle.net/f18513hw/. The code functions properly in JSFiddle. I copied and pasted the code into my Textpad, saved it in my htdocs folder o ...

The jQuery script fails to function properly within dynamically loaded content via ajax

After browsing through various articles and seeking help from Google, I've managed to do some basic coding as a designer. However, there's a complex problem that I'm struggling with. On my main page, I have news displayed and when scrolling ...

Issues with data communication in AJAX and Node JS/Express post requests

I'm currently exploring Node.js and I'm running into an issue with app.post. Everything seems to be working fine, as I can see the console log whenever the action is executed. However, the data sent by AJAX from main.js does not seem to be receiv ...

Animate a div once the parent section becomes visible while scrolling

I previously had this function working, but it seems that I have somehow messed it up in the process. My current setup includes a scroll hijack feature that navigates users to a new section or card each time they scroll. The script adds a visible class w ...

Refreshing the DeckGL HexagonLayer upon changes to the data array/Initiating a reload for the DeckGL HexagonLayer

I am currently using DeckGL along with React to showcase data on an OpenStreetMap. My goal is to incorporate filters to allow for different views of the data I possess. The main issue I encounter is the inability to refresh the layer representing the data ...

How can you prevent a tag from firing in Google Tag Manager by identifying a particular script included in the HTML code

Seeking advice on modifying our Google Tag Manager container as I am a novice when it comes to GTM. Encountering an issue with IE8 on pages utilizing Fusion Charts resulting in a javascript error in gtm.js. Upon investigation, it appears to be related to a ...

Choosing groupings of courses

I am looking to dynamically load divs with different combinations of classes from an external file using jQuery's load function, but I am struggling with grouping them correctly. $("#somediv").load("somefile.html .class1"); // loads all divs with c ...

The conditional statement in node js is failing to execute properly

I am looking to implement a system where, after logging in, the system will check the user's role and redirect them accordingly based on their role (admin or user). The 'role' field is of integer type. Below is my code snippet: router.post( ...

Exploring the power of Vue.js with dynamic HTML elements and utilizing Vue directives within Sweet Alert

new Vue({ el: '#app', data(){ results: [] } }); I need assistance with implementing Vue directives, events, etc. within the markup of a Sweet Alert. The goal is to display an alert using Sweet Alert that include ...