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

Craft a function within the recompose library

As I was exploring the compose function in recompose library by @acdlite to combine boundary conditions for Higher Order Components, I came across two different implementations of the compose function: const compose = (...funcs) => funcs.reduce((a, b) ...

What is the process for altering the color of an HTML output depending on its values?

I created a simple HTML code to showcase some outcomes. The possible results are SUCCESS, Failure, and Still Failing. I want these results to be displayed with corresponding colors, such as green for SUCCESS, and red for both Failure and Still Failing. I ...

User interaction with a checkbox triggers a state change in Angular

Here is the code snippet I am working with, where clicking should set the checked value to false: @Component({ template: ` <input type="checkbox" [checked]="checked" (change)="onChange()"> ` }) export class AppC ...

Obtain the distinct highest value for every vertical axis on a bar graph

I'm facing an issue with my code where I am appending multiple SVG elements and generating 3 different charts. The problem is that the maximum value evaluated from the y.domain() for each y-axis is taken as the maximum value from all of my data. Is t ...

Updating the parent component upon navigating from the child component in Angular app

Struggling with updating the parent component after routing from a child component. Through research, I've learned that ngOnInit only runs once. Any way to work around this issue? I've experimented with different lifecycle hooks, but no luck so f ...

Javascript deepmerge causes issues with objectid manipulation

While I have experience with javascript, using node.js for the first time has presented some challenges. I am attempting to form a basic query to be used in mongoose, with the intention of adding conditions later on. I am currently employing deepmerge to m ...

Display or conceal several elements using JQUERY/HTML upon hovering

Here is the current progress: <div style="position: relative;"> <a href="#games"> <div class="sidenavOff"> <img src = "images/card_normal.png" /> <img src = "images/category_icons/icon_games.png" style = "position: a ...

transferring a string parameter from PHP to a JavaScript function

I have been searching for a way to transfer a string (stored as a variable $x) from PHP to JavaScript. I came across several code solutions, but I am wondering if these strings need to be declared as global variables? Even after declaring it as a global va ...

Properly managing mouseover events on a flipped div: tips and tricks

I created a div that flips when clicked using some HTML and CSS code. It works perfectly in Firefox 39 and Chrome 43. Here is the markup: <div class="flip-wrapper flippable-wrapper" id="fliptest-01"> <div class="flip-wrapper flippable ...

How to effectively utilize multiple Vue instances in your project?

My inquiry is somewhat linked to a similar question on Stack Overflow, but I am uncertain about the level of discouragement towards the approach discussed in relation to Vue. In my situation, I am working on a project where the DOM is generated entirely b ...

Unable to retrieve data from Meteor find query

I have a collection created in collections.js portfolioItems = new Mongo.Collection('portfolioitems'); This collection is then subscribed to in subscriptions.js Meteor.subscribe('portfolioitems'); And published in publications.js M ...

Error in sending Ajax form

I have a form that is set up to send data to a server. When the form is in its regular HTML format, everything works smoothly and all data is successfully transmitted to the server without any issues. However, as soon as I switch the form to use AJAX for s ...

How can I retrieve the selected value from an Angular 2 dropdown menu when it changes, in order to utilize it within a function?

I am currently working on creating a dropdown menu with multiple options. When a user selects an option, I need to make an API call that requires an ID parameter. Inside my component.ts file, I have defined an array containing the values like this: valu ...

Managing JavaScript with Scrapy

Spider for reference: import scrapy from scrapy.spiders import Spider from scrapy.selector import Selector from script.items import ScriptItem class RunSpider(scrapy.Spider): name = "run" allowed_domains = ["stopitrightnow.com"] start_urls = ...

Performing AJAX callback function on success in jQuery

I've been trying to troubleshoot an error but none of the solutions I've found so far seem to be working for me. I have an ajax request set up to retrieve JSON data from the server. I can see the JSON data that I want to capture when using consol ...

The Mongoose Pre-Save Hook triggers successfully, yet fails to save an extra field (without relying on model.update)

Striving to implement a numbering system in my schema to fetch the next issue number has led me to a perplexing situation. Despite setting it up as a pre-save hook in Mongoose and everything seeming to work, the 'number' field stubbornly refuses ...

Is it possible to create dynamic backgrounds using Twitter Bootstrap's responsiveness?

Is there a way to create a responsive image arrangement for backgrounds on a website? Imagine having different background images load based on various screen resolutions. Additionally, it would be advantageous to specify different behaviors such as having ...

Troubles with configuring the Express server in relation to the public directory

After creating two separate bundles for my server and client, I encountered an issue where the client bundle is not being downloaded by the browser when accessing the root route. To address this, I instructed Express to treat the public/ folder as a freel ...

In JavaScript with Node.js, how can one verify a file's size and only download the initial kilobyte of the file?

When using Javascript/Node JS to download a file, you can check the file size and download only the first kilobyte of the file. This is useful if you want to hash the first kb and compare it with the hash of the complete file. If the hashes match and the ...

javascript issue with attribute manipulation

My current struggle involves setting the attribute of an element through programming, but I keep encountering an error in Firebug: obj.setAttribute is not a function. Since I am working with jQuery, allow me to provide some additional code for better conte ...