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

Is there a way to terminate an ongoing axios request?

I have been encountering a memory leak issue whenever my browser is redirected away from this component. To resolve this, I tried to cancel it using the cancel token, but unfortunately, it doesn't seem to be working as expected. I am puzzled as to why ...

Prevent redundant entries in MongoDB with Mongoose to optimize database efficiency

Hi there, I'm currently exploring MongoDB and Mongoose. My goal is to prevent users of my API from storing duplicate contact names in the Mongo database, but unfortunately it's not working as expected. This is how I have set up the validation: b ...

The Alphavantage was acting strangely when I ran a Google script

After following a tutorial video on YouTube, I was confident that my Google script for Google Sheets was working perfectly. However, I encountered two strange issues that I just can't seem to figure out. The code below is exactly what I need - it ...

Redux: Double rendering issue in mapStateToProps

I've recently delved into learning Redux, and I've encountered an issue that's been on my mind. import React, { useEffect } from "react"; import { connect, useDispatch } from "react-redux"; import Modal from "../Moda ...

onkeypress() method not triggering the function

I have a task to prevent users from typing "%" in a textArea, so I implemented the following: However, even after clicking inside the text area, I can still type '%', indicating that my onkeypress function is not working properly or there is an ...

How to send URL parameters to a different page with the help of express and Node.js

Hey there, I'm currently working on a chat app which you can check out here. I'm in the process of enabling users to join specific rooms by typing in a URL like , assuming they are logged in. I manage user login and signup with passwords. Here&ap ...

Ways to retrieve a variable within the init() function

My current project involves using datatables along with ajax to display information dynamically. Below is the code snippet I am working with: // Setting up the module var DatatableAdvanced = function() { // Examples of Basic Datatables var _c ...

Enhancing user experience with AngularJS: Harnessing ng-Click for seamless task management on display pages

I'm struggling with my TodoList in AngularJS. I need help creating the ngClick function for the "addTodo" button. My goal is to send the entire form data to another page where I can display the tasks. Can someone guide me on what needs to be added to ...

Is it achievable to use node.js/express-session to store only a single property in the session?

Environment: Node.js, Express, express-session Question: Can individual session properties be saved in express-session, rather than saving the entire session at once? Background: By default, express-session saves the session data at the end of each http ...

Strategies for positioning identical Highcharts series next to one another

I am currently utilizing highcharts to create column charts. My column chart consists of multiple series, structured like this: Here is the code I am working with: $(function () { var chart; $(document).ready(function() { ...

"error": "Connection Failure", "type": "AxiosError",

I recently worked on a project using Vue.js and making API requests with axios. Here is my code snippet: axios({ method: "POST", url: http://abcd.com:5000/start-recording?roomId=${this.roomId}, headers: { 'Access-Control-Allow-Origin': ...

Encountering issues when attempting to render a function within the render method in React

When attempting to render the gridWithNode function inside the render method, I encountered an error message stating: "Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant ...

Keep a vigilant eye on the peak utilization of memory within the Node.js process

I am in search of a way to effectively monitor the maximum memory usage in a Node.js process, regardless of whether there are memory leaks or not. The processes in question include both real applications and synthetic tests. My expectation is that it sho ...

Issues with receiving data on $.ajax POST request

If you'd like to check out my website Please use the following login details (case sensitive): Username: stack Password: stack Click on the tab labeled "yourhours." The main goal is to send all input box data to a database. At the moment, I am fo ...

What is the best way to incorporate a unique font with special effects on a website?

Is there a way to achieve an Outer Glow effect for a non-standard font like Titillium on a website, even if not everyone has the font installed on their computer? I'm open to using Javascript (including jQuery) and CSS3 to achieve this effect. Any sug ...

What is the most effective method for utilizing JSON as a database?

For my upcoming offline mobile web app project, I am considering using JSON to mirror some of my database tables and storing the data in localStorage. (Although Web SQL Database is an option, its future-proofing capabilities are questionable.) Initially, ...

The critical role of an administrator in an Express API system

I developed an express API for creating admin users, allowing them to perform tasks like adding categories. I utilized mongodb in my user model file, setting regular users as 0. While testing on postman, I encountered an issue where the request "localhost: ...

Is it possible to generate a triangular attachment below a div element?

My designer sent me a unique design and I'm wondering if it's possible to replicate using HTML, CSS, or JavaScript? https://i.stack.imgur.com/spB71.png I believe it can be done with CSS by creating a separate div positioned absolutely under the ...

The functions that have been imported are not defined

I encountered a Error in created hook: "TypeError: _api__WEBPACK_IMPORTED_MODULE_0__.default.$_playerApi_getPlayers is not a function" issue while using Webpack through Vue CLI on my webpage. Below is the structure of my project directory: . + main.js + ...

Please be aware that any fabricated comments will not be displayed in the posts object

-I have made an EDIT at the bottom of my original post -For my plunker, please visit this link Currently, I am learning AngularJS by following a tutorial located here. At this moment, I am stuck on the step called 'Faking comment data'. I have ...