Error encountered: MongoDB cast exception - nested subdocument

Check out this schema design:

var messageSchema = new Schema({
  receivers: [User],
  message: String,
  owner: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  }
});

var userSchema = new Schema({
  name: String,
  photo: String
});

var inboxSchema = new Schema({
  messages: [Message],
  owner: {
    type: Schema.Types.ObjectId,
    required: true
  },
  sequence: Number
});

When attempting to create a new message with the following code:

var newMsg = {
  receivers: ['<id1>', '<id2>'],
  message: 'Hello world',
  owner: '<userId>'
}

Inbox.findOneAndUpdate({
  owner: '<userId>'
}, {
  $push: {
    messages: newMsg
  },
  $set: {
    sequence: '<sequence>'
  }
}, {
  upsert: true
}, callback);

An error is thrown:

MongooseError.CastError "Cast to undefined failed for value [object Object] at path "messages""

What could be causing this issue? How can it be resolved?

Appreciate any help.

Answer №1

The field in the message object that expects an array of objects following the User schema is 'receivers', not an array of ObjectId's hexadecimal string representation. Therefore, you must replace the 'receivers' array with the actual objects represented by the ids. Here is an example:

var newMessage = {
    receivers: ['<id1>', '<id2>'],
    message: 'Hello world',
    owner: '<userId>'
};

Users.find({ "_id": {"$in": newMessage.receivers} }, function (err, users){
    // handle error
    if (err) throw err;

    // update
    newMessage.receivers = users;
    Inbox.findOneAndUpdate(
        { owner: '<userId>'}, 
        {  
            $push: { messages: newMessage  },
            $set: { sequence: '<sequence>' }
        }, 
        { upsert: true}, callback
    );
});

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

Error in Layout of Navigation Panel and Tabbed Pages

Working on a school project, I encountered a challenge. I found two useful solutions from the W3 website - a sticky navigation bar and the ability to include tabs on a single page for a cleaner presentation of information. However, when trying to implement ...

Switching from PHP to jQuery or JavaScript can make for a

I've been attempting to convert this PHP code to jQuery or JavaScript without success. I'm still learning about jQuery and JavaScript Check out the original PHP code: <?php // Set timezone date_default_timezone_set('UTC'); ...

Is there a way to automatically hide divs with the style "visibility:hidden" if they are not visible within the viewport?

Currently, I am working on developing a mobile web app. Unfortunately, Safari in iOS 5.1 or earlier has limited memory capabilities. In order to reduce memory usage while using css3 transitions, I have discovered that utilizing the css styles "display:none ...

Loading an empty CSS file in Node.js

Just starting out with node.js, and I could really use some help with a small css and image issue that I'm facing. I've streamlined my html and .js for clarity. Despite trying everything, the css and image just won't load. My form and server ...

Is it possible to retrieve a local variable from a JavaScript function and utilize it outside of its

I've been struggling for hours to access a local variable outside of a function, but I can't figure out where I went wrong. Here's the code: Here's my edited code: if (lastMsg.toUpperCase().indexOf("@TEST") > -1) { var myPy ...

Sliding an image from the left side to the right, and then repeating the movement from left to right

I am currently working on a CSS effect for some images. My goal is to have an image appear from the left side, move towards the right side, then reappear from the left and repeat this cycle. I managed to achieve this using the code below: @keyframes sli ...

A step-by-step guide on building a custom contact form using ReactJS and transmitting the data through an API with Express

In my quest to utilize ReactJS for building a contact form and seamlessly sending the data to my email address, I embarked on creating a contact form within my App.js file. import React, { Component } from 'react'; import axios from 'axios& ...

Switch the appearance between two elements

In my HTML table, I have different levels of content - from main "contents" to nested "sub-contents" and even deeper "sub-sub-content". My goal is to hide all sub-content within the content cell that I click on. <table> <tr class=' ...

Utilize Discord.js to send a message and patiently await your response

I am facing an issue while trying to code a Discord bot. I'm struggling to make it wait until the user inputs 'Y' or 'N'. Specifically, I am currently working on the ban command and everything seems to be functioning well until the ...

Having trouble with DataTables functionality in Laravel blade views?

Blade template with a query: @extends('2a.layouts.master') <link rel="stylesheet" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"> <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <script s ...

Attempting to Create a New User and Display the Resulting Page Using JavaScript and Handlebars Templates

I've implemented a form that allows users to input data. Once the user hits "Add User", they are successfully added to the database. However, instead of transitioning to the next page as expected, the form remains populated on the current page. The h ...

Sending variable boolean values to a VueJS component

How can I assign dynamic properties to a VueJS Component using VuetifyJS? Below is an example of VuetifyJS code that constructs a select field element: <div id="app"> <v-app id="inspire" style="padding: 10px; "> ...

javascript implementing number formatting during keyup event

When I try to format a number in an input field on the keyup event, I receive a warning in my browser console that says "The specified value "5,545" cannot be parsed, or is out of range." The value in the input field also gets cleared. How can I solve this ...

Can we trigger a POST request when the user reaches the bottom of the page?

Many inquiries share this issue, but the solutions I've come across only explain how JavaScript functions, not how to handle routing in this context. I'm currently struggling with implementing the HTML and routing components for an infinite scro ...

Set up an array data by extracting values from an array prop within a Vue component

Within my Vue component, I am dealing with an array prop called selectedSuppliers that consists of objects. My goal is to set up a data property named suppliers and initialize it with the values from selectedSuppliers. However, I do not want any modificati ...

Adjust the object's width and position based on the window's width

I am currently attempting to adjust the width of a box and the position of a btn based on the size of the window. Q1. How can I eliminate the excess white space located behind the scroll bar? (I have already set it to 100%..) Q2. After clicking the ...

Steps for automatically retrying a failed expect statement in Jest

In my React application, I am utilizing Jest for performing unit testing. One aspect of my application involves a Material UI date picker with next and previous buttons. The selected date is displayed in the browser URL. Each time the user clicks on the ne ...

What could be the reason for the React component not re-rendering even after its prop has been updated?

One of the challenges I'm facing with an application I'm currently working on is a re-render issue. To simplify, let's say we have two components - DisplayElement1 and DisplayElement2. In this scenario, DisplayElement2 iterates through a ba ...

The Vue/Vuetify wrapper component does not automatically pass on the `hide-details` parameter to the input component

I recently crafted a custom wrapper for the v-select input using Vuetify. Along with custom properties, I utilized the v-bind="$props"attribute to inherit all props. Upon testing, I observed that while this method applies to most props, it doesn ...

The jQuery validation feature is failing to function properly within a bootstrap modal

I'm facing an issue with the jQuery validation plugin in my express app sign-up form that uses Bootstrap for the front-end. Despite setting rules and messages for name, email, and phone number fields, the validation is not functioning correctly. Below ...