What could be causing the type error to show up in my JavaScript file?

Why is this error occurring?

I am currently studying web development through Colt Steele's web bootcamp and encountered this issue.

$ node user.js
mongo connection is open
D:\web development practice\mongoose_relationship\Models\user.js:44
    u.addresses.push({
      ^

TypeError: Cannot read properties of null (reading 'addresses')
    at addAddress (D:\web development practice\mongoose_relationship\Models\user
.js:44:7)
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/relationshipDemo', { useNewUrlParser: true })
    .then(() => {
        console.log("mongo connection is open")
    })
    .catch(e => {
        console.log("oh no mongoose connection error");
        console.log(e);
    })

const userSchema = new mongoose.Schema({
    first: String,
    last: String,
    addresses: [{
        _id: { id: false },
        street: String,
        city: String,
        state: String,
        country: String
    }]
})

const User = mongoose.model('User', userSchema);

const makeUser = async () => {
    const u = new User({
        first: 'Harry',
        last: 'Potter'
    })
    u.addresses.push({
        street: 'baker street',
        city: 'london',
        state: 'london',
        country: 'uk'
    })
    await User.deleteMany();
    const res = await u.save();
    console.log(res);
}

const addAddress = async (id) => {
    const u = await User.findById(id);
    u.addresses.push({
        street: 'florida street',
        city: 'new york',
        state: 'new york',
        country: 'usa',
    })
    const res = await u.save();
    console.log(res);
}

addAddress('62ceae58cbb52805b8150ce9');

Answer №1

It appears that you forgot to include a semicolon ";" at the end of your parentheses.

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

modifying a record in MongoDB with the help of Mongoose

I need help with updating a collection in MongoDB using Mongoose. function check (db) { var hours = 60 * 60 * 1000 var threeHours = 3 * hours; var lastUpdated = null; db.collection("profile").find({userName: "Rick"}).toArray(function(er ...

Utilizing a preset canvas for the renderer can lead to issues

As I dive into tutorials on three.js, I encounter a challenge when using my predefined canvas elements for the renderer. Everything works smoothly if I let three.js create the renderer DOM element. However, when I attempt to retrieve the canvas using getEl ...

There was an unexpected error in angular.js while trying to work on a calendar widget based on angular-ui-calendar. The error message indicated that the argument 'fn' was expected to be a function but instead received Moment

I came across a similar topic earlier on Stack Overflow, but unfortunately, the issue wasn't resolved. So, I've decided to revisit this question and address it myself this time. In my app.js file, which is where my main module for the app is ini ...

Strategies for avoiding text selection interference with onMouseMove event

I am in the process of adding a "resize handle" to adjust the width of my left navigation panel. This handle, represented by a div, triggers an onMouseDown() event that calculates the necessary widths and applies them to the relevant elements during subseq ...

Utilize the Material UI SelectField component as a reference for handling onChange events

I'm facing a challenge with my form that contains over 15 SelectField components. I want to avoid creating multiple change handler functions, but I can't figure out how to identify the specific select field that triggered the change event in orde ...

Creating a spherical polyhedron, such as a soccer or football ball, using three.js

I am trying to create a spherical polyhedron using three.js, like a soccer or football ball, but I am having trouble figuring out how to do it. My goal is to achieve a shape that is spherical in nature and similar to a truncated icosahedron (with faces co ...

The submission is processed regardless in Firefox

var form0 = document.forms[0]; form0.onsubmit = function(e){ alert("form submitted"); var email = form0.elements["email"].value; var url = "https://bpi.briteverify.com/emails.json?address="+email+"&apikey=my-key&callback=emailResult"; ...

Consolidating and organizing data according to a Mongodb Connection

I am currently exploring the feasibility of my requirements in Mongodb. Any suggestions on more effective methods to achieve the desired outcome are welcome. At present, I have 2 collections: vehicles (This collection contains unstructured vehicle data s ...

What is the reason behind having several node modules directories within every project?

I'm just starting out with JS development and I have a question about the size of node modules. It seems that when many projects accumulate, we end up having to delete the node_modules folder because it takes up so much space. So, why isn't there ...

Try utilizing MutationObserver to monitor changes in various nodes

I am faced with a situation where I have elements in my HTML that are dynamically populated with text from an API. My goal is to check if all these elements have a value and then trigger a function accordingly. The current code I have only allows me to obs ...

What steps can be taken to verify that the submitted data is a legitimate numerical pair?

When I receive a string, it should be in the following format: number,number For example: 34.798,52.123 I need to verify that the number is indeed in this format before assigning it to variables and performing calculations. There is also a concern that ...

Filtering a List Using Angular

I am working on a code where I need to filter a list of elements based on the option selected from a combobox. Currently, my code is error-free but I am unable to successfully filter the list. Can someone please guide me on what steps I should take next? ...

Executing Selenium WebDriver to interact with a hidden element

Hello, I am interested in learning how to interact with hidden elements and disable them using Selenium WebDriver. I've managed to achieve this with Selenium 1 by using the following code: selenium.click(id="idOfHiddenField"); Unfortunately, this a ...

Encountering issues with the Sequelize Model.prototype.(customFunction) feature malfunctioning

While attempting to define a customFunction within the Sequelize model, I encountered an error: TypeError: user.getJWT is not a function at User.create.then (/projects/test/a/app/controllers/UserController.js:22:29) Below is the code snippet from ...

The error message "Joomla! 2.5 and Virtuemart 2.0.18a - $.facebox is not recognized"

I encountered an issue while using Joomla! 2.5.8 and Virtuemart 2.0.18a where I received the error message "Typeerror $.facebox is undefined in vmprices.js (line 67)" when attempting to Add to Cart. Interestingly, switching back to the default Joomla! temp ...

The state is not being configured accurately

In my ReactJs project, I have a model Component with a picture that is displayed. I want to pass the data of the clicked picture, which can be neither raw data nor a URL. I have implemented a handler that can delete the picture (if pressed with the Ctrl k ...

Placing emphasis on an object that appears following a period of waiting

I'm currently working on enhancing the accessibility of a slider that will be featured on my website. The goal is to create an effect where, after clicking (or pressing enter) on the first slide, the focus shifts to the second slide element, allowing ...

Experiencing difficulties coding SVGs

Struggling with manipulating SVGs in JavaScript and looking to extend a line by clicking a button? Check out this code snippet I've included in the head tag: <script type="text/javascript"> x=135; y=135; var container = document.getElementById( ...

Unraveling the Mystery of jQuery AJAX Response: Where Have I Gone Astray?

$.ajax({ type: 'POST', url: 'place/add', data: { lat: 45.6789, lng: -123.4567, name: "New Place", address: "123 Main St", phone: "555-1234", review: "Great place!", cat ...

What is the method for initializing fancybox with the precise image index?

My current usage of fancybox involves the following code snippet: $("a[rel=Fancy" + UserId + "].Items").fancybox({ 'autoscale': 'false', 'cyclic': true, 'transitionIn': 'elastic', & ...