Encountering a Mogoose validation error while attempting to write a test involving nested objects

I'm currently developing a small application that utilizes javascript, node.js, mongoDB, and mongoose. Within this application, I have two collections - users and groups. Each group contains an array of users.

User Schema: {_id:{type: String, required: true}, FirstName: {type: String, required: true}, ..}

Group Schema{_id:{type: String, required: true}, users:[{user: userSchema}] }

While writing an API unit test using Mocha and Superagent, I encountered a validation error when inserting a sample document for the group with nested objects for the users.

Could you assist me in identifying the issue with this example?

var userSchema = 
{
    _id: {
        type: String,
        required: true,
    },
    profile: {
        firstName: {
            type: String, 
            required: true
        },
        lastName: {
            type: String, 
            required: true
        }
}; 

var GroupSchema = 
{
    _id: {
        type: String, 
        required: true
    },
     users:[{
         user: User.userSchema
     }]
};
it('can query group by id', function(done) {
  var users = [
    { _id: 'az', profile: {firstName: 'a', lastName: 'z'}},
    { _id: 'bz', profile: {firstName: 'b', lastName: 'z'}},
  ];

  User.create(users, function(error, users) {
    assert.ifError(error);
    Group.create({ _id: 'ab', users: [{ _id: 'az', profile: {firstName: 'a', lastName: 'z'}}, { _id: 'bz', profile: {firstName: 'b', lastName: 'z'}}] }, function(error, doc) {
    assert.ifError(error);
    var url = URL_ROOT + '/api/groups/id/ab';

    superagent.get(url, function(error, res) {
      assert.ifError(error);
      var result;
      assert.doesNotThrow(function() {
        result = JSON.parse(res.text);
      });
      assert.ok(result.group);
      assert.equal(result.group._id, 'ab');
      done();
    });
  });
  });
});

Error Message:

 Uncaught ValidationError: ChatGroup validation failed: users.1._id: Cast to ObjectID failed for value "bz" at path "_id", users.0._id: Cast to ObjectID failed for value "az" at path "_id", users.0.user.profile.lastName: Path `user.profile.lastName` is required., users.0.user.profile.firstName: Path `user.profile.firstName` is required., users.0.user._id: Path `user._id` is required., users.1.user.profile.lastName: Path `user.profile.lastName` is required., users.1.user.profile.firstName: Path `user.profile.firstName` is

Answer №1

Your GroupSchema definition seems to be incorrect:

var GroupSchema = 
{
    _id: {
        type: String, 
        required: true
    },
     users:[{
         user: User.userSchema
     }]
};

The use of User.userSchema in the test should actually be an array within the users field:

var GroupSchema = 
{
    _id: {
        type: String, 
        required: true
    },
     users:[{
         type: User.userSchema // need to specify 'type' here
     }]
     // OR simply: users: [User.userSchema]
};

If you still want to stick with your original schema, then make sure to structure your test data like this:

  var users = [
    { user: { _id: 'az', profile: {firstName: 'a', lastName: 'z'}} },
    { user: { _id: 'bz', profile: {firstName: 'b', lastName: 'z'}} },
  ];

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 jQuery failing to serialize the form data?

I have a question regarding my form. When I try to serialize it using a jQuery script, the output is empty. Could someone please assist me with this issue? Here is a snippet of my form: <form id="tabb2"> <!-- *************************** ...

Google Maps fails to load when triggered by the jQuery show() function

One issue I'm facing is that the Google Map is not loading after the show() function is called in jQuery. Initially, I use display:none to close a division on page load. After some research, I found out that it can be resolved by using google.maps.eve ...

Javascript problem: Trouble with event.clientX position

I found a great resource on learning javascript at this website, I'm having trouble understanding the code snippets in function XY(e, v), specifically these two lines: event.clientX + document.documentElement.scrollLeft and event.clientY + document ...

``Is there a way to align components with the same width side by side horizontally

I have a situation where I need to align three components, a radio button and two select fields, on the same row within a container. Currently, they are displaying on separate rows but I want them to be in three columns on a single line. I tried following ...

How come the action doesn't trigger in my React/Redux application?

Currently, I am in the process of developing a small application that incorporates modals. Instead of relying on pre-made packages like react-modal, I have taken the initiative to build the modal functionality from scratch. 1) Defining a reducer located i ...

The Angular controller that has been injected into the app is not defined

In an effort to enhance my simple Angular app, I decided to modularize it. I separated the controller into its own file within a dedicated directory. By employing dependency injection, I ensured the controller's availability in the app module. Combini ...

Can Javascript have IDs within hrefs?

Is it possible to insert an href with an id inside the runConfirm function? My goal is to display a pop-up after clicking accept, where the accept button triggers the query from isset. Below is the code for accepting: $displaybody .= "<tr> <td&g ...

React - Dealing with rendering issue when toggling a button using LocalStorage and State

For quite some time now, I've been struggling with a particular issue... I'm encountering challenges in using the current state to display a toggle button that can both add and remove an item from local storage. The code below manages to add and ...

Ng-repeat seems to be having trouble showing the JSON data

Thank you in advance for any assistance. I have a factory in my application that utilizes a post method to retrieve data from a C# function. Despite successfully receiving the data and logging it to the console, I am facing difficulties in properly display ...

What is the best way to retrieve an AJAX response from a different domain?

Are there alternative methods to retrieve AJAX response and access data from a different domain without requiring changes on the server-side code? While YQL offers this feature, it comes with limitations such as a maximum of 1000 calls per hour for free u ...

Discover the complete file path using node.js incorporating the express-busboy module

I am currently utilizing node.js and express-busboy for the purpose of uploading a file via a file input form to my server. Once uploaded, the file will be stored in a directory with a path resembling something like root/useruploaded/formattached/somerando ...

End the ajax request if it exceeds the specified timeout period

Currently, I am running an ajax call to test the timeout function on my server. To see if it works properly, I intentionally suspended my server. Despite receiving a timeout message in the client after one second, the call persists in Firebug. I have sear ...

"The communication between systems failed" - specifically for Internet Explorer

I am attempting to create a new window using JavaScript and populate it with the HTML content from the current window. This is similar to a print preview in a new window, but with a different CSS style. function openPrintPreview() { var printWindo ...

Is there a way for me to access videos sorted by genre preferences of the users?

In the following explanation, it is evident that a user may possess one or multiple videos and one genre. Is there a method by which videos can be sorted based on a specific genre? class User include Mongoid::Document include Mongoid::Timestamps r ...

What is the best method for extracting span text using selenium?

<p id="line1" class=""><span class="bot">Do you have a short-term memory?</span><span id="snipTextIcon" class="yellow" style="opacity: 1;"></span></p> I want to extract this text: Do you have a short-term memory? This ...

What is the most effective approach to building this function in React JS rather than the existing .map method?

Hello, I'm fairly new to all of this so please bear with me. I've been working on developing a search function for my app, but I've encountered a problem. The search function in my header component is being rendered like this in my index: &l ...

Illustrator export script for efficient saving of images as web-friendly jpg files

Looking for assistance with creating a script in illustrator CC2017 that can automatically export files to web (legacy) as JPG, save the file, and then close it. I have 700 files, each with 2 art boards, and manually exporting and saving each one is time ...

Refresh tab controllers in Angular JS on every click event

Is there a way to refresh the tab controller every time a tab is clicked? Here's the current code: $scope.tabs = [ { id: 'tab1', title: 'tab1', icon: 'comments', templateUrl: 'tab1/tab1.tpl.html&ap ...

How can server-side paging be best implemented in Express.js using Mongoose?

I am currently working on a project using my own MEAN stack. In my new project, I have a collection that I am paging with Express on the server side. It returns the page size each time (e.g., 10 results out of a total of 2000) and the total rows found for ...

Encountering a multithreaded error when attempting to connect Erlang with MongoDB

When connecting to my MongoDB server using localhost with ports 27019, 27020, and 27021, I encountered an issue where if I connect with 5 threads and each thread reads data, exceptions are thrown. However, if I reduce the number of threads to 3 or less, ev ...