Refreshing user details: using Express with Node.js

I have been struggling with this task for hours without any success. My goal is simple - I just want to update user data, but it seems like there's something I'm not grasping in my app.post(..) function. Despite feeling confident that I was handling the problem correctly, I keep encountering an error saying "undefined is not a function" at the line where I initialize a new activity instance as "var activity = new activity({title: req.body["activities.title"]});". I'm completely lost..any assistance would be greatly appreciated!

var passport = require('passport');
var Account = require('./models/user');
var mongoose = require('mongoose');
var LocalStrategy = require('passport-local').Strategy;
var connect = require('connect');
var activity = require('mongoose').model('activity').schema;
module.exports = function (app, models) {

  app.get('/home', function (req, res) {
      if (req.user){ console.log('userin');
    }
      res.render('home', { user : req.user });

  });

  app.get('/register', function(req, res) {
      res.render('register', { });
  });

  // more functions...

Below is the content of my models file:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    passportLocalMongoose = require('passport-local-mongoose')
var Schema = mongoose.Schema;

// model schema definitions...

// exporting schemas
module.exports = mongoose.model('user', user);
var activity = mongoose.model('activity', activities);

This is what my app file looks like:

var express = require('express');
var fortune = require('./lib/fortune.js');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var session = require('express-session');
var mongoose = require('mongoose');
var Account = require('./models/user');
var connect = require('connect');
var bodyParser = require('body-parser');
var app = express();

// setting up handlebars

// more setup and route configurations...

I am using the Handlebars templating engine for my form as shown below:

<form role='form' action="/schedule" method="POST">
title:<br>
<input type="text" name="activities[title]">
<br>
<input type="submit" value="Submit">
</form>

Answer №1

You have declared the variable "activity" twice in your code.

var activity = require('mongoose').model('activity').schema;
// additional code goes here
app.post('/schedule', function(req, res){
   var activity = new activity({title: req.body["activities.title"]});

The 'new' keyword is mistakenly used with the same variable name as the one already declared. To fix this issue, consider using a different variable name like:

app.post('/schedule', function(req, res){
    var newActivity = new activity({title: req.body["activities.title"]});

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

"Error: 'res' variable is undefined within the EJS template

My task is to dynamically display different templates based on the route, which in this case are /edit and /new. I need a condition to determine whether to show tabs or something else. In my router.get('/edit' cb) function, I tried checking if r ...

Using Typescript to Define Mongoose Schemas

Currently exploring the creation of a user schema in TypeScript. I've observed that many people use an interface which functions well until I introduce a message involving username.unique or required property. No error code present: import {model, mo ...

Where is the assistant "select" function?

I've been working on displaying the selected option from MongoDB. Despite multiple attempts and researching various sources, I keep encountering the following error: "Error: Missing helper: 'select'". Below is the contents of my handlebar_h ...

Having difficulty accessing and updating data in a database while using Discord.js

My goal is to enable staff to respond to the last direct message (DM) by using ~reply <message> instead of ~dm <userID> <message>. However, before I can do that, I need to store the user's ID in a database to identify the last person ...

Using Node Express to fill out forms with AJAX

Is it possible to update a specific section of a webpage using AJAX without having to refresh the entire page? If so, how can this be achieved correctly? //Get Book router.get('/form/:id', (req, res) => { Book.findOne({ _id: req.params ...

Error encountered when trying to match routes in two separate Angular applications within an Express app: "Cannot find any routes that match

Greetings (please pardon any language errors as English is not my first language) Like many others, I have an Angular app running in Express and decided to create separate Angular apps for the admin and users (mainly because the navigation bar was becomin ...

Error in Node and Express: Unable to access route

Currently, I am in the process of developing an Express application and running into some obstacles with routing. While my '/' route is functioning perfectly fine, other routes are not working as expected. Despite researching similar questions fr ...

What is the best way to link CSS files from libraries that are downloaded using npm?

For instance, let's say I installed a package: npm install --save package and it gets saved in ./node_modules/package/ Inside that folder, there might be a directory named styles and within that directory, you could find style.css. How can I link ...

Removing a document from an array within a MongoDB collection

I have a MongoDB schema that looks like this. { userID: 19202, products: [{ id: 020, name: 'first' }] } My goal is to remove items from the product array based on their id. I tried using the following command but it didn't give any ...

Steps for installing npm on Ubuntu operating system

To set up the mocha test framework, npm is required. To install it, follow these steps: 1. sudo apt-get install npm 2. npm install -g mocha After running the first command, you may encounter the following error: user@dell:~/mochatest$ sudo apt-get in ...

Exit status 1: Permission denied when attempting to use nvm

Previously, I installed Node.js without using NVM and then completely removed it by uninstalling and deleting all related files. My operating system is Windows 10. While running Powershell as an administrator works fine, I am facing issues using Yarn in ...

Leveraging Material-UI in Electron Environment

I'm currently working on an electron app using React and incorporating Material-UI for the user interface. I've added a datepicker and timepicker to a component, but when clicking on the input in the electron app, nothing happens. I'm unsure ...

Understanding NodeJS Code

As a newcomer to nodejs, I've been delving into some code and trying to grasp its concepts. Could someone kindly guide me in understanding the following code snippets? My inquiries might be basic, but please note that I'm on a learning curve with ...

I am interested in delivering a blended, divided response containing JSON and a string using Express

I am currently in the process of integrating ChatGPT into my Node/Express project and I have a specific requirement. I would like to initially send some metadata in JSON format to the client before streaming the response from ChatGPT as it comes in. Every ...

Troubleshooting a Docker-Compose issue: UnhandledPromiseRejectionWarning with Node and PostgreSQL connection

I am currently working on connecting the postgres and node containers in my setup. Here are the details: My yml file: version: "3" services: postgresDB: image: postgres:alpine container_name: postgresDB ports: - "5432:54 ...

Tips for maintaining a user's session post-login with Passport and Express JS

I recently set up a node backend using express and integrated Passport for authentication purposes. My application has a route called /login for logging in and another route called /me to retrieve information about the currently logged in user. Below is t ...

The perplexing simplicity of closure

Currently, I am endeavoring to enhance my knowledge of JavaScript closures. Let's consider the following two scenarios in Node.js: function A(){ console.log(data); //this will result in a null pointer } module.exports = function(data){ re ...

Issue TS2339: The object does not have a property named 'includes'

There seems to be an issue that I am encountering: error TS2339: Property 'includes' does not exist on type '{}'. This error occurs when attempting to verify if a username is available or not. Interestingly, the functionality works ...

Restrictions on File Size in Express Server (Exceeding 50MB)

Is there a method to upload files larger than 50 mb on the express server? I keep encountering the file size limitation of 50 mb. Appreciate any help. Thank you. ...

How to send multiple collections to a view using Express and Mongoose

I've encountered an issue while trying to pass multiple mongoDB queries to my EJS view using the code below. Surprisingly, only the "mvl" query is getting passed down successfully. The "extras" query seems to be unavailable as none of its values show ...