When attempting to add an item to an array within a sub-document using Mongoose and MongoDB, the error message "Property 'messages' not found" is returned

I am working with four different models: teacher, student, teacherMessageSchema, and studentMessageSchema. The teacherMessageSchema is a subdocument within the 'teacher' model under the messages: [teacherMessageSchema] property, while the studentMessageSchema is a subdocument within the 'student' model under the messages: [studentMessageSchema] property. I am trying to figure out how to add an object to the arrays teacherMessageSchema and studentMessageSchema. This is what I have attempted so far:

module.exports.sendMessage = (req, res) => {
    
    let {sender, receiver, msg} = req.body;
    var hex = /[0-9A-Fa-f]{6}/g;

    sender = (hex.test(sender)) ? mongoose.Types.ObjectId(sender) : sender;
    receiver = (hex.test(receiver)) ? mongoose.Types.ObjectId(receiver) : receiver;

    Teacher.findById({_id: receiver}, function(err, member) {
        console.log(member, 'member');

        member.messages.push({msg});

        console.log('messages', member.messages)
        
        member.save(function(err, updated) {
            if (err)
                res.send(err);
    
            res.json(updated, 'updated');
        });
    });
}

However, the property messages cannot be found.

Teacher and Student Model

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const crypto = require('crypto');
const {studentMessageSchema, teacherMessageSchema} = require('./message');


const userSchema = new Schema({
    name: {
        type: String,
        trim: true,
        required: true,
        maxLength: 32
    },
    email: {
        type: String,
        unique: true,
        trim: true,
        required: true,
        lowercase: true
    }
}, {timestamps: true});


const studentSchema = userSchema.clone();
studentSchema.add({
    messages : [studentMessageSchema]
});

const teacherSchema = userSchema.clone();
teacherSchema.add({
    messages : [teacherMessageSchema]
});



const User =  mongoose.model('User', userSchema);
const Student = mongoose.model('Student', studentSchema);
const Teacher = mongoose.model('Teacher', teacherSchema);

module.exports = {
    User,
    Student,
    Teacher
}

Message Model

const mongoose = require('mongoose');
const Schema = mongoose.Schema;


const messageSchema = new Schema({
    "contentInfo" : {
        "viewed" : {type: Boolean, default: false},
        "msg" : {type: String, required: true},
        "createdAt" : { type : Date, default: Date.now }
    }
});

const studentMessageSchema = messageSchema.clone();
studentMessageSchema.add({
        "receiver" : {
        type: Schema.ObjectId
    }
});

const teacherMessageSchema = messageSchema.clone();
teacherMessageSchema.add({
    "sender" : {
        type: Schema.ObjectId
    }
});


module.exports = {
    messageSchema,
    teacherMessageSchema,
    studentMessageSchema
}

Controller Message

const User = require('../models/user');
const Student = require('../models/user');
const Teacher = require('../models/user');
const mongoose = require('mongoose');

module.exports.sendMessage = (req, res) => {
    
    let {sender, receiver, msg} = req.body;
    var hex = /[0-9A-Fa-f]{6}/g;

    sender = (hex.test(sender))? mongoose.Types.ObjectId(sender) : sender;
    receiver = (hex.test(receiver))? mongoose.Types.ObjectId(receiver) : receiver;

    Teacher.findById({_id: receiver}, function(err, member) {
        console.log(member, 'member');

        member.messages.push({msg});

        console.log('messages', member.messages)
        
        member.save(function(err, updated) {
            if (err)
                res.send(err);
    
            res.json(updated, 'updated');
        });
    });
}

Answer №1

Make sure to create a message model before pushing the msg. Once you have the model, push it to the user.messages array.

let {studentMessageSchema}= require("path of messeages Schema/")

module.exports.sendMessage = (req, res) => {
    
    let {sender, receiver, msg} = req.body;
    var hex = /[0-9A-Fa-f]{6}/g;
    sender = (hex.test(sender))? mongoose.Types.ObjectId(sender) : sender;
    receiver = (hex.test(receiver))? mongoose.Types.ObjectId(receiver) : receiver;

     //create a studentMessage Model
    let studentMessage =  new studentMessageSchema({
      contentInfo : {
          msg : msg
       },
      receiver : receiver
     })

    Teacher.findById({_id: receiver}, function(err, member) {
        console.log(member, 'member');

        member.messages.push({studentMessage });

        console.log('messages', member.messages)
        
        member.save(function(err, updated) {
            if (err)
                res.send(err);
    
            res.json(updated, 'updated');
        });
    });
}

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

The focus functionality in Angular seems to be malfunctioning

Having trouble with simple focus in Angular <div class="search pull-right tab-{{ showDetails2 }}" data-ng-click="showDetails2 = !showDetails2; showDetails = false; showDetails1 = false;searchFocus();"> html <input type="text" data-ng-model="mod ...

"Learn the technique of adding a new data attribute before every element in a step-by-step

I am currently working with the following HTML code: <div id="elem"> <div data-foo="aaa"></div> <div data-foo="aaa"></div> <div data-foo="aaa"></div> <div data-foo="bbb"></div> < ...

Preserving the information from a webpage by utilizing casperjs for scraping and saving table data

What is the most efficient way to preserve table data collected during a web scraping process with casperjs? Saving it as a file after serializing into a json object. Sending an ajax request to php and then storing it in a mysql database. ...

Guide on embedding PHP code into a HTML div element using JQuery

I am having trouble loading PHP code into a div tag to display the results. The code I have listed below does not seem to work for me. If anyone can offer assistance in resolving this issue, I would greatly appreciate it. Here is the code snippet: <h ...

After the rendering process, the React Component member goes back to a state of

One issue I encountered is related to a component that utilizes a separate client for making HTTP requests. Specifically, when trying to use the client within a click event handler, the call to this.client.getChannel() fails due to this.client being undefi ...

Produced inputs and preset values

I have a question regarding the use of generated input elements in my App's form. I want to keep it as simple as possible, which is why I am using native form reset for these elements. It appears that the 'default value' becomes bound to th ...

Encountering path import errors when developing a sample webpack site within a TypeScript library

Struggling to integrate my custom library with TypeScript and Webpack. Import errors are causing headaches, despite smooth sailing in CLion. Running tsc within the project directory is error-free, unlike when running npm run dev in the examples/webpack di ...

An error occurs when using Node.js with Passport and Express Validator because the req parameter is undefined

Currently, I am setting up my route and I want to incorporate Passport for user authentication during the sign-up process: router.post('/user/signup', passport.authenticate('local.signup',{ successRedirect: '/user/profile&apos ...

What is the best approach to repurpose a component when small adjustments are needed?

Can a customized slider component be created in React that can be reused with slight variations? For example, having the second one include a 13% field. View image description here ...

Live AJAX inquiries in progress

Is there a way to track the number of active AJAX requests in jQuery, Mootools, or another library similar to Prototype's Ajax.activeRequestCount? I am looking for a method that can be used across different libraries or directly through XMLHttpRequest ...

Error message: Unable to modify headers after they have already been sent-NodeJS, MongoDB, and Mongoose

While working on a basic todo MEAN application with a remote database, I've encountered a strange issue. Whenever I try to update or delete a record (not always, but mostly), an error is thrown: events.js:160 throw er; // Unhandled 'error& ...

The regex routes are now unable to efficiently serve static assets

Question Is it possible to use regex or the built-in URL processor in Express to properly load static files? Expected Behavior Express should match the initial route it encounters and load files as usual. Actual Behavior Error messages indicate that ...

Passing variables from AJAX response to PHP using a passthru function

In my PHP file, I have implemented a functionality where certain checkboxes are checked and upon clicking a button, a JavaScript file is triggered. The JavaScript code snippet used is as follows: $.ajax ({ type: "POST", url: "decisionExec.php", ...

How to trigger an Angular JS route without loading a view

Could someone help me with calling the /auth/logout url to get redirected after a session is deleted? app.config(['$routeProvider',function($routeProvider) { $routeProvider .when('/auth/logout',{ controller:'AuthLo ...

Exploring the capabilities of NEXTJS for retrieving data from the server

When trying to retrieve data from the nextjs server on the front end, there is an issue with the code following the fetch() function inside the onSubmit() function. Check out the /test page for more details. pages/test const onSubmit = (data) => { ...

Two conflicting jQuery plugins are causing issues

In my journey to learn jQuery, I encountered an issue while working on a website that utilizes a scroll function for navigating between pages. The scripts used in this functionality are as follows: <script type="text/javascript" src="js/jquery-1.3.1.mi ...

Display various JavaScript function outputs in an HTML table for convenient tracking

Thanks to a helpful user on this platform, I was able to capture data from a JavaScript function and display it in an html table. However, I now have another query. How can I execute the function multiple times during page load and record the results in ...

Is there a method to retrieve the data type along with the data using Sequelize?

Can someone help me retrieve both the data type and data of an attribute using axios and sequelize? ...

Exploring the magic of the (!!!) operator in JavaScript!

The !! operator proves to be quite helpful when converting non-boolean data types into Boolean values, mainly for "True" conditions. However, when it comes to false conditions, is using !!! necessary? ...

What are the best approaches for managing asynchronous calls while verifying uniqueness in Backbone.js?

For client or server-side applications using Backbone, I am working on creating a validation function that includes checks for uniqueness to MongoDB or a REST call depending on the environment. Both of these calls are asynchronous by nature, but it seems l ...