Mongoose: An unexpected error has occurred

Recently, I developed an express app with a nested app called users using Typescript. The structure of my app.js file is as follows:

///<reference path='d.ts/DefinitelyTyped/node/node.d.ts' />
///<reference path='d.ts/DefinitelyTyped/express/express.d.ts' />
///<reference path='routes/Users.ts' />

import express = require("express");
import http = require("http");
import path = require("path");
import us = require("./routes/Users");

var app = express();

// all environments
app.set('port', 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('env', 'development');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('less-middleware')({ src: __dirname + '/public' }));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
    app.use(express.errorHandler());
}

app.get('/', (req, res) => {
    res.render("index", {
        title: "Express Main Page"
    });
});


// Users app
app.use(us.Users.users);

http.createServer(app).listen(app.get('port'), () => {
    console.log('Express server listening on port ' + app.get('port'));
});

However, when it comes to storing data using mongoose and mongodb, that's where the issue arises. Here's a glimpse into what the Users.ts file entails:

/// <reference path='../d.ts/DefinitelyTyped/node/node.d.ts' />
/// <reference path='../d.ts/DefinitelyTyped/express/express.d.ts' />
/// <reference path='../d.ts/DefinitelyTyped/mongoose/mongoose.d.ts' />

import express = require("express");
import mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/SimpleBlog");

export module Users {

    // Exporting information about the user class
    export var users: Express = express();
    export var base_URL: string = "/users";

    // Creating Schemas
    var UserSchema = new mongoose.Schema({
        email: String,
        name: String,
        age: Number
    });

    // Fetching users
    var db_Users = mongoose.model('Users', UserSchema);

    var list;
    db_Users.find({}, (err, docs) => {
        list = docs;
        console.log(docs);
    });

    // Route for base URL
    users.get(base_URL, (req, res) => {
        res.render("Users/index", {
            title: "User List",
            user_list: list
        });
    });


    // Route for POST request
    users.post(base_URL + "/add", (req, res) => {

        try {
            console.log(req.body['name']);

            new UserSchema({
                name: req.body['name'],
                email: req.body['email'],
                age: req.body['age']
            }).save(function (err, docs) {
                    if (err) { console.log(err); }
                });
        } catch (Exception) {
            console.log(Exception);
        }
        res.redirect(base_URL);
    });

    users.get(base_URL + "/add", (req, res) => {
        res.render("Users/add", {});
    });

}

Upon attempting to save data, I encountered a

[TypeError: object is not a function]
error message.

The registration form displayed at users/add works correctly in rendering the jade file. It's also worth mentioning that there seems to be no issue with express.bodyParser() since console.log(req.body['name']); successfully outputs the name from the post request.

If anyone could provide assistance or insights on this matter, it would be greatly appreciated.

Answer №1

The syntax you are using for Mongoose is incorrect.

In reference to this specific line:

// Retrieving users
var db_Users = mongoose.model('Users', UserSchema);

This line actually returns a Model function or constructor. You will utilize this result to create instances of a User. Given your current setup with Users, UserSchema, and the User namespace, it can be a bit confusing. Let's clarify by renaming it:

// Retrieving users
var UserModel = mongoose.model('User', UserSchema);

It seems like the class represents a single User, rather than multiple Users.

When you need to create an instance of a User, you should instantiate the UserModel class instead of the schema itself:

new UserModel({
    name: req.body['name'],
    email: req.body['email'],
    age: req.body['age']
}).save(function (err, docs) {
        if (err) { console.log(err); }
});

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

Tips for ensuring text remains within a div container and wraps to the next line when reaching the edge

Currently, I am working on a flash card application using Angular. Users can input text in a text box, and the text will be displayed on a flash card below it. However, I have encountered an issue where if the user types a lot of text, it overflows and mov ...

TypeScript Definitions for Material-UI version 15

Is there a Material-UI v15 TypeScript definition file in the works? I need it for a project I'm working on and as a TypeScript newbie, I want to make sure the custom file I've begun is accurate. ...

The data sent through the webhook must be in the form of either a string or a Buffer object that accurately reflects the raw content of the

const express = require("express"); const app = express(); app.set("port", process.env.PORT); app.post( "/webhook", express.raw({ type: "application/json" }), (request, response) => { const sig = request.headers["stripe-signature"]; // ...

Send a JSON string directly to Google Cloud Storage without the need for a file upload

When I need to receive data in the form of a JSON string from an external source and then upload it directly to Google Cloud Storage without saving it as a local file first, is there a way to accomplish this task? Thank you. storage .bucket(bucketName) ...

Creating a Map in TypeScript from an Array

I have a series of TypeScript objects structured like this: interface MyObject { id: string, position: number } My goal is to transform this array into a map format where it shows the relationship between id and position, as needed for a future JSON ...

How can we avoid multiple taps on Ext.Button in Sencha Touch?

Currently working on a Sencha Touch game, but struggling with users tapping buttons multiple times. Looking for a simple solution to prevent multiple tap events in the app.js file so that only one tap event is executed even if a user taps or presses for an ...

Learn the best practices for integrating the options API with the Composition API in Vue3

Using vue3 and vite2 Below is a simple code snippet. The expected behavior is that when the button is clicked, the reactive 'msg' variable should change. It works as expected in development using Vite, but after building for production (Vi ...

React-xarrows is a stunning display of multiple arrows overlapping each other in a mesmerizing fashion

I am currently using the react-xarrows library within my project to connect tables in a diagram. However, I have encountered an issue where multiple links between two tables cause the arrows to overlap, resulting in only one visible link instead of the int ...

Encountering special symbols in the ID of a form element triggers an error message in jQuery validator, stating 'Unrecognized expression'

One of the challenges I am facing is that I have a form with elements that have ids containing special symbols. For example: The id="$FormData[1]$PersonData[1]$PhysicalPerson[1]$PersonName[1]$Affix[@type='qualification' and @position='prefi ...

Why does the Hamburger Menu shift my website's logo when it opens?

I'm in the process of implementing a hamburger menu on my website. My attempts have involved adjusting the positioning of both the #logo and .topnav elements. Code Snippet source function myFunction() { var x = document.getElementById("myTopn ...

What is the best way to apply DateRange filtering in a Kendo Ui Grid?

Currently I am working with the Kendo Ui Grid and attempting to implement filtering by DateRange. Here is a snippet of my current code: HTML: <kendo-grid-column field="createdate" title="Creation Date" width="150"> <ng-template kendoGridFilterC ...

What is the best way to implement a Cascading Async Select feature using @atlaskit/select library?

I recently delved into React and I'm currently exploring how to create a Cascading Async Select (for example, selecting Country then City) using @atlaskit/select. As per the documentation, I utilized the option loadOptions in the initial Async Select ...

Utilize MySQL/Javascript to determine percentages

I'm facing a challenge with an SQL query in Entrinsik's Informer. I need to calculate a percentage using JavaScript on the result, but unfortunately, Informer cannot access data down columns (such as the total for the percentage). Therefore, I ha ...

Displaying a message when there are no results in Vue.js using transition-group and encountering the error message "children must be keyed

Utilizing vue.js, I crafted a small data filter tool that boasts sleek transitions for added flair. However, I encountered an issue with displaying a message when there are no results matching the current filters. Here's what I attempted: <transit ...

The Art of Validating Forms in Vue.js

Currently I am in the process of developing a form with validation using Vue, however, I've run into some errors that are showing up as not defined even though they are currently defined. HTML <form class="add-comment custom-form" @submit="checkF ...

What is the process for sending JavaScript with an Ajax request?

Working with ajax and javascript for the first time, I'm no expert in web development. Here is the code I've written and tested so far. I have a select div containing some options. <select id="month" onchange="refreshGraph()"> When an op ...

How can I display several custom markers that are constantly updating on a Google map with MySQL and PHP?

Currently, I am using the following code to generate markers on a Google map by retrieving data from a database. However, the issue I am facing is that it only generates one marker instead of all the markers stored in the database. & ...

Issue with Heroku deployment: Express module not detected

I'm currently facing an issue while trying to deploy my Node.js app that includes some getter and setter functions. Despite selecting the Node.js environment on Heroku and providing all necessary environment variables, I keep encountering errors relat ...

Establish Default Values and Validate the POST Submission

const requiredKeys = {title: 'string', src: 'string', length: 'number'}; const optionalKeys = {description: 'string', playcount: 'number', ranking: 'number'}; const internalKeys = {id: 'numbe ...

Enhance React component props for a styled component element using TypeScript

Looking to enhance the properties of a React component in TypeScript to include standard HTML button attributes along with specific React features such as ref. My research suggests that React.HTMLProps is the ideal type for this purpose (since React.HTMLA ...