Error: Mongoose failed to cast DBrefs value to ObjectId

I am facing an issue with my Team Schema and Match Schema setup. I want the home/away teams in the Match Schema to refer to the Team object. However, I am encountering an error while trying to save the Team. I suspect there might be an issue with the Schemas or the way I am saving the Match. Can someone provide assistance?

The code snippets I have so far:

Team.js extract

var Team = new Schema({
  'key' : {
    unique : true,
    type : Number,
    default: getId
  },
  'name' : { type : String,
              validate : [validatePresenceOf, 'Team name is required'],
              index : { unique : true }
            }
});

module.exports.Schema = Team;
module.exports.Model = mongoose.model('Team', Team);

Match.js extract

var util = require('util');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Team = require('../schemas/Team').Schema;

var Match = new Schema({
  'key' : {
    unique : true,
    type : Number,
    default: getId
  },
  'hometeam' : {
    type : Schema.ObjectId,
    ref : 'Team'
  },
  'awayteam' : {
    type : Schema.ObjectId,
    ref : 'Team'
  }
});

module.exports = mongoose.model('Match', Match);

index.js

  app.get('/match', function(req, res) {
    var key = 1356136550152; // Reading
    Team.findByKey(key, function(err, team) {
      if(err) {
        res.send("An error occurred");
      }
      if(!team) { 
        res.send("The team does not exist");
      }
      var match = new Match();
      match.hometeam = team;
      match.save(function(err) {
        if(err) {
          util.log('Error while saving Match: ' + util.inspect(err));
          res.send("An error occurred while saving the match");
        } else {
          res.send("Saved the match");
        }
      });
    });
  });

ERROR:

Error while saving Match: { message: 'Cast to ObjectId failed for value "{ name: \'testTeam\',\n  _id: 50d500663ca6067226000001,\n  __v: 0,\n  key: 1356136550152 }" at path "hometeam"',
  name: 'CastError',
  type: 'ObjectId',
  value: 
   [ { name: 'testTeam',
       _id: 50d500663ca6067226000001,
       __v: 0,
       key: 1356136550152 } ],
  path: 'hometeam' }

Error with team._id

Error while saving Match: { [MongoError: E11000 duplicate key error index: testdb.matches.$team.name_1  dup key: { : null }]
  name: 'MongoError',
  err: 'E11000 duplicate key error index: testdb.matches.$team.name_1  dup key: { : null }',
  code: 11000,
  n: 0,
  connectionId: 8,
  ok: 1 }

db.matches.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "ns" : "testdb.matches",
        "name" : "_id_"
    },
    {
        "v" : 1,
        "key" : {
            "key" : 1
        },
        "unique" : true,
        "ns" : "testdb.matches",
        "name" : "key_1",
        "background" : true,
        "safe" : null
    },
    {
        "v" : 1,
        "key" : {
            "team.key" : 1
        },
        "unique" : true,
        "ns" : "testdb.matches",
        "name" : "team.key_1",
        "background" : true,
        "safe" : null
    }
]

Answer №1

Within the index.js file, the correct syntax is:

match.hometeam = team._id;

as opposed to:

match.hometeam = team;

UPDATE

After receiving a new error message, it appears that there is a unique index on the matches collection that is referencing fields that do not actually exist. To resolve this, you can drop the index in the shell using:

db.matches.dropIndex('team.name_1')

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

In Angular 2, transferring data from a parent route to a child route

I have set up a route named "home" with three child routes: documents, mail, and trash. Within the home route component, there is a variable called 'user'. While I am familiar with various methods of passing information between parent and child c ...

What causes the server to give an incorrect response despite receiving a correctly read request?

After setting up a new project folder and initializing NPM in the Node.js repl, I proceeded to install the Express package. In my JavaScript file, I included the following code: const express = require('express'); const app = express(); ...

My element is not being animated by Elementbyclass

Without Using JQUERY The animation I'm trying to create isn't functioning properly. I attempted to utilize document.getElementsByClassName, but it's not working as expected. There are no errors, but the element is not animating correctly. ...

What could be the reason for the absence of the loading sign in Chrome, even though it appears when the code is run on Firefox?

I implemented a function to display a loading screen on my HTML page with Google Maps integration. However, when I called the function popUpLoadingScreen() and dismissLoadingScreen() to show and hide the loading message while rendering map markers, the loa ...

Organize a list in AngularJS by breaking it down based on its headers and displaying them in

As someone who is new to angularJs, I am looking to convert an app to angularJs but I have encountered a roadblock: The custom accordion markup I am working with is as follows: <div class="accord_main_wrap" ng-controller="catController"> <di ...

I'm encountering inexplicable duplications of elements on my Wordpress site

Here is an example of my template header: <header> <?php if ( function_exists( 'jetpack_the_site_logo' ) ) jetpack_the_site_logo(); ?> <a class="menu-toggle">menu</div> <?php wp_nav_menu( array('them ...

What is the best way to empty input, select, and textarea fields after performing a clone operation

I am currently working on creating a form to display items and need a fresh text field when the user clicks the ADD button. function addNewItem() { //ADD ROW AND CLONE var table = document.getElementById('tbl'); var tbody = document.create ...

Tips for dynamically styling a Styled Component with all the CSS housed in an external file

My goal is to dynamically render a Styled Component. In the past, it was simple because all styling was contained within the component itself. However, I now strive to maintain a separation of concerns by storing the CSS in an external file. While this app ...

What is the process for updating the class of the target button?

I am new to using Vue and struggling to achieve a specific functionality. I have multiple buttons and I want to ensure that only one button can be selected at a time. Currently, I have tried implementing it with the following code: :class="isActive ? ...

What is the best way to utilize JavaScript for both server-side and client-side development, all while effectively sharing code between the two

Recently, I've been brainstorming a side project that I want to dive into for fun. As I explore options, I find myself searching for examples, libraries, and frameworks that could streamline the process of sharing code between the client and server. ...

The process of running npm build is not resulting in the creation of the bundle.js file

I've read through many Q&A threads where people are facing the same issue, but I still can't figure out what's wrong with my code. When I run 'sudo npm run build', no bundle.js file is being created.** This is my code: index ...

Different types of video formats used for html5 video players

Looking for some guidance here. I'm currently in the process of developing a website that allows users to upload their own videos. For the video player, I've opted for the HTML5 player by . My main concern is ensuring that the HTML5 player can on ...

Validating forms using ajax, php, and mysql for seamless user input processing

I'm currently in the process of creating a login form that includes an instant email address verification feature against my database. Despite my efforts and attempts to make this functionality work, I have faced challenges in getting it to function ...

Attempting to reach <p> from numerous web pages

Currently, I am working on a project where I need to extract text data from various websites. I have successfully managed to retrieve the text data using <p> tags. I would really appreciate any assistance with this task. Thank you! ...

Adjusting color of fixed offcanvas navbar to become transparent while scrolling

After creating a navbar with a transparent background, I am now using JavaScript to attempt changing the navigation bar to a solid color once someone scrolls down. The issue is that when scrolling, the box-shadow at the bottom of the navbar changes inste ...

The Uglify task in Grunt/NPM is having trouble with this particular line of JavaScript code

Whenever I execute grunt build, Uglify encounters a problem at this point: yz = d3.range(n).map(function() { return k.map(x -> x[1]); }), An error message is displayed: Warning: Uglification failed. Unexpected token: operator (->). I have recentl ...

What is the best way to retrieve specific JSON data from an array in JavaScript using jQuery, especially when the property is

Forgive me if this question seems basic, I am new to learning javascript. I am currently working on a school project that involves using the holiday API. When querying with just the country and year, the JSON data I receive looks like the example below. ...

Experience an enthralling carousel feature powered by the dynamic ContentFlow.js

My website features a cover flow style carousel with 7 images: <!-- ===== FLOW ===== --> <div id="contentFlow" class="ContentFlow"> <!-- should be place before flow so that contained images will be loaded first --> <div class= ...

:host background color may be missing, but the font size has been boosted?

Check out this demo where the CSS is applied to the :host element or <hello>. The font size increases but the background color remains unchanged. What do you think? styles: [` :host { font-size: 2rem; background-color: yellow; }`] }) ...

Do GPU-intensive animations get impacted by the CPU's load?

I have set up a special compositing layer for a div with the following unique styles: div { position: absolute; height: 50px; width: 50px; background: #900; top: 100px; left: 200px; will-change: transform; transform: translateZ(0); } Afte ...