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

I've noticed that the NextJs router appears to be significantly slower in comparison to React

I currently have a website that is built in both React Js and Next Js. The issue I am currently encountering is that the router in NextJs is noticeably slower compared to react-router-dom. It takes almost 2-3 seconds to change the route. To experience th ...

Sending a POST request using Node.js Express: A step-by-step guide

Looking for help on sending a post request from node.js Express with data passing and retrieval. Preferably a straightforward method like cURL in PHP. Can anyone assist? ...

Internet Explorer automatically moves the cursor to the beginning of a textarea when it gains

When trying to insert "- " into an empty textarea, I am facing issues with Internet Explorer. While Firefox and Chrome work perfectly fine by inserting the text as expected, IE causes it to jump to the beginning of the textarea after insertion. Therefore, ...

Rewriting URLs in Angular 2

I am a beginner in Angular 2 and I am currently working on a project that requires URL rewriting similar to that of ' '. In Zomato, when you select a city, the city name appears in the URL like ' ', and when you select a restaurant, t ...

What is the best way to convert exponential values to decimals when parsing JSON data?

var value = '{"total":2.47E-7}' var result = JSON.parse(value); Looking to convert an exponential value into decimal using JavaScript - any suggestions? ...

What steps should I follow to enable a tooltip in this specific situation using qtip?

In my database, I have tables for venues, venue types, and map icons with the following relationships: A venue belongs to a venue type A venue type belongs to a map icon Each venue result is shown on the index page as a partial. Each partial ...

if and elsif JSON with Angular

Currently, I am working on completing a task within our project. To provide more context, I have a field with items that I must select. Once I choose an item, another field appears in which I must select additional elements. These elements need to be sen ...

Is there a way to limit the number of items displayed in the feed to just 10 using the Flickr API?

I am currently utilizing the Flickr API to showcase some images, however I only want to display 10 or fewer items in the feed results. How can I limit the number of items displayed to less than 10 without seeing a limit parameter? https://api.flickr.com/s ...

The fulfillment of the post route for the login page is awaiting a request in the browser using Express Node.js

The router is currently waiting for a response (request pending) router.post('/loginpost',(req,res,next)=>{ var email=req.body.email; var password=req.body.password; var selectsql=`SELECT * FROM client WHERE em ...

Creating an accordion feature within an ng-repeat using AngularJS based on user clicks

When I click on the span with ng-click="click_subcat(opp.ct_nm);, the content is loaded within the <span ng-click="click_pdms(opp.sbct_nm);" style="color:white;cursor:pointer">{{opp.sbct_nm}}</span>. The issue arises when I click on that span a ...

`searching for a timestamp saved as a string in a MongoDB database`

Storing date and time strings separately in a MongoDB collection is common practice. Each document typically includes fields like: Date: "05/16/2014", Time: "11:00", Coach: { coachId: "15b62940-1df8-42df-a30e-d52f4169c9f8", coachName: "xxxxxx ...

The process of converting a data:image base64 to a blob is demonstrated in this code snippet

Seeking a way to convert data:image base64 URLs to blob URLs. Below is the original code that generates the base64 URLs: <script> $(window).load(function(){ function readURL() { var $input = $(this); var $newinput = $(this ...

The extensive magnetic scrolling functionality in Ionic 2 sets it apart from other frameworks

Hi everyone, I could really use some assistance! I've been working on developing an Ionic 2 App and my navigation setup is not too complex. I have a main menu where clicking on an item opens another menu with a submenu. From there, if I click on an i ...

Removing CSS from a Link in react-router-dom

My attempt to create unique divs for different pages using the code in my home.js didn't go as planned. <Link to="Subject1"> <Product title="The Lean Startup" image="https://images-na.ssl-images-amazon.co ...

Error: The variable "details.date.getTime" is not defined and cannot be accessed

Currently, I am utilizing https://github.com/zo0r/react-native-push-notification to display notifications. Specifically, I am using scheduled notifications with datetimepicker. Previously, I have successfully used this in another project without any errors ...

Don't forget to expand or collapse

I'm struggling to make this work. My goal is to initially display 50 characters and show the rest when the "read more" button is clicked, and vice versa with "read less." Another problem I've noticed is that when I click the back browser button, ...

Leveraging Angular, ExpressJS, and NodeJS to enable users to download a text file by simply clicking a

My goal is to incorporate a download button that allows users to download a document from my node.js server. Behold the stylish download button: https://i.sstatic.net/s4CjS.png My tech stack includes Angular for the front-end and node.js along with exp ...

Tips for organizing AJAX code to show images and videos in HTML with a switch case approach

I have 2 tables, one for images and one for videos. Within my HTML code, I have three buttons: slide_image, video, and single_image. Using iframes, I am able to load images and videos on the same page. When I click on the slide_image button, it displays im ...

Could someone please assist me in figuring out the issue with my current three.js code that is preventing it from

Recently, I decided to delve into learning three.js and followed the getting started code on the official documentation. However, I encountered a frustrating issue where the scene refused to render, leaving me completely perplexed. Here is my index.html: ...

Enforce directory organization and file naming conventions within a git repository by leveraging eslint

How can I enforce a specific naming structure for folders and subfolders? I not only want to control the styling of the names (kebab, camel), but also the actual names of the folders and files themselves. For example, consider the following paths: ./src/ ...