Make Connections between Schemas with MongoDB, Express, and Mongoose

I need to establish relationships between my schemas in the "Movie" entity so that I can access information from other entities like:

  • Category
  • Actor
  • Director
  • Studio

Right now, I am testing with categories.

This is the code I have written:

controllers/movie.js


const create = async (req, res) => {
    const content = req.body;

    const category = await Category.findById(content._id);
    const actor = await Actor.findById(content._id);
    const director = await Director.findById(content._id);
    const studio = await Studio.findById(content._id);
    
    const newMovie = new Movie({
        ...content,
        category,
        actor,
        director,
        studio
    });

    const savedMovie = await newMovie.save();

    category.movies = [...category.movies, savedMovie._id];
    await category.save();
    actor.movies = [...actor.movies, savedMovie._id];
    await actor.save();
    director.movies = [...director.movies, savedMovie._id];
    await director.save();
    studio.movies = [...studio.movies, savedMovie._id];
    await studio.save();

    res.status(201).json({
        message: 'Movie created successfully',
        movie: savedMovie
    });
};

models/movie.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const {ObjectId} = mongoose.Schema; 

const movieSchema = new Schema(
  {
    title: {
      type: String,
      required: true,
    },
    year: {
      type: Number,
      required: true,
    },
    duration: {
      type: String,
      required: true,
    },
    rating: {
      type: String,
      required: true,
    },
    score: {
      type: String,
      required: true,
    },
    category: {
      type: ObjectId,
      ref: "Category",
    },
    description: {
      type: String,
      required: true,
    },
    director: [{
      type: ObjectId,
      ref: "Director",
    }],
    actor: [{
      type: ObjectId,
      ref: "Actor",
    }],
    studio: {
      type: ObjectId,
      ref: "Studio",
    },
    poster: {
      type: String,
      required: true,
    },
    trailer: {
      type: String,
      required: true,
    },
  },
  {
    timestamps: true,
  }
);

module.exports = mongoose.model("Movie", movieSchema);

models/category.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const {ObjectId} = Schema;
const categorySchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },
    movies: [
      {
        type: ObjectId,
        ref: "Movie",
      }
    ]
  },
  {
    timestamps: true,
  }
);

module.exports = mongoose.model("Category", categorySchema);

controllers/category.js


const Category = require('../models/category');

const create = async (req, res) => {
    const category = Category(req.body);
    
    res.status(201).json(
        await category
        .save()
        .then(result => {
            res.status(201).json({
                message: 'Category created successfully',
                category: result
            });
        })
    );
};

Next, I will show the error after making my request

Request

POST http://localhost:3000/api/v1/movies HTTP/1.1
Content-Type: application/json

{
        "title": "The Matrix",
        "year": 1999,
        "duration": "136 min",
        "rating": "R",
        "score": "8.7",
        "categoryId": "62650106b643152d5fc5204e",
        "description": "A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.",
        "directorId": ["626502e956cd00fe36692bf9"],
        "actorId": ["626501fc56cd00fe36692bf2"],
        "studioId": "626502ac56cd00fe36692bf7",
        "poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BNzQzOTk3OTAtNDQ0Zi00ZTVkLWI0MTEtMDllZjNkYzNjNTc4L2ltYWdlXkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_SX300.jpg",
        "trailer": "https://www.youtube.com/embed/m8e-FF8MsqU"
}

Response

TypeError: Cannot read property 'movies' of null at create (C:\Users\Ernesto\Desktop\streaming-backend\src\controllers\movie.js:26:36) at processTicksAndRejections (internal/process/task_queues.js:95:5)

Answer №1

It's clear from the errors what the issue is.
One of the error messages reads

"message": "Path 'trailer' is required."
, indicating that the movie attribute 'trailer' is missing. Let's delve into why this is happening.

This is the snippet of code used to save a movie:

const newMovie = new Movie({
        content,
        category: category._id,
        actor: actor._id,
        director: director._id,
        studio: studio._id
    });             
    
    
    try {
        const result = await newMovie.save();

The absence of trailer suggests that it may be related to the content. The line content = Movie(req.body) implies that content becomes an object. To address this, I will adjust the data passed to the constructor:

const content = {insert properties here}
const newMovie = new Movie({
        {insert properties here} //Updated value of `content`
    });

If you're still unsure about the problem, the answer awaits below:

Utilize ...content instead of just content

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 was working with node.js when I encountered the following issue: 'server' is declared but its value is never read.ts(6133) from the line "var server = app.listen(3000, listening);"

While working on the 8.6 lesson in the api2 folder, I encountered an error/bug. Upon inspection of my server.js file, I identified and rectified the issue. However, when I revisited the api1 folder for the 8.5 lesson, everything was functioning correctly a ...

Converting text/plain form data to JSON using Node.js - step by step guide

I am currently working on a Node.js application to execute a POST call to an API for placing an order. However, the data I receive in our app is in text/plain format and not JSON. This is the current format of the data: TypeOrder=buy Coin=BTC AmountCoin= ...

Error: Unable to access property of an undefined value (ExpressJS/POST)

I have gone through all the similar questions but none of the solutions are working for me. I am facing an issue with my node js app where I am unable to print the input text from a form while using body-parser. Here is my index.ejs file: <fo ...

The path mappings specified in the tsconfig.json file are not resolving correctly during the

Everything runs smoothly with my imports during coding, but after building the project using tsc, the imported files are not resolving to valid paths. This is how my tsconfig.json looks: { "compilerOptions": { "target": "ES2 ...

Running both Express and Websocket on the same port within the same file

Currently, I have set up two applications that are able to send real-time messages to each other using WebSocket, and also generate a random link using express.js. I have hosted both React apps on my VPS host and now I am looking to secure the WebSocket co ...

The variable 'X' in Node.js is not been declared

I've been struggling with this problem, trying to fetch my most recent tweets as an array using the npm module https://github.com/noffle/latest-tweets. However, no matter how I approach it, I always encounter errors such as 'posts is not defined& ...

Getting matched records from two different collections in MongoDBHow can you get matching records from two

How can I retrieve data from the deposit and coin_info collections where the coin id is the same in both collections? I attempted to use the lookup aggregation method, but ended up with an empty array as a result. var mongoose=require('mongoose&apos ...

Express.js: Defining a base route can cause issues with resolving static files

I'm currently working on a project using express.js and react.js, but I've encountered some issues that I can't seem to find solutions for. I have set up a base directory where the express server is located, and within that, there's a ...

Oops! An issue occurred while trying to convert a circular structure to JSON in Node.js Express. This error originated from an object with the constructor 'Topology' and the property 's'

This is my index.js file where I am attempting to implement search functionality using query string. Although I am receiving the query from the client, I am encountering an error in the campground.find() function. app.get('/results', (req, res) = ...

Submit your document using the connect-form tool

I ran into an issue while trying to upload a file using connect-form. I found that in order to successfully upload the file, I had to disable the bodyParser() function in my app.js. If I kept bodyParser() enabled, it would result in an error: loading forev ...

My Express server is having trouble loading the Static JS

I'm feeling frustrated about this particular issue. The problem seems to be well-solved, and my code looks fine, but I can't figure out what's wrong . . . I have a JavaScript file connecting to my survey page, which I've added at the b ...

Incomplete JSON response being received

We set up an express server to call an API and successfully requested the JSON object in our server. However, we are facing an issue where the JSON data is getting cut off when being displayed as a complete object on the client side. We tried using parse i ...

What is the best way to generate a search link after a user has chosen their search criteria on a webpage?

In my search.html file, I have set up a form where users can input their search criteria and click the search button to find information within a database of 1000 records. The HTML part is complete, but I am unsure how to create the action link for the for ...

We encountered a 404 error when using $.getJSON with an incorrect URL and [object%20Object]. How did this occur?

I have set up my front end server using grunt-contrib-connect on http://127.0.0.1:8888, with express running as my backend server on http://127.0.0.1:3000. My front-end framework is Ember, and I have enabled cross-domain requests by adding Access-Control-A ...

Utilizing NodeJS and Express to enhance the client side for showcasing an uploaded file

My knowledge of nodeJS, AJAX requests, and routing is still in its infancy. After following a tutorial on nodejs and express examples, I managed to get everything working on the server-side. However, I'm facing difficulty displaying the uploaded file ...

Encountering a problem in a MEAN application while sending a PUT request

I am encountering an issue while developing a todos app in MEAN stack with MongoDB installed locally. The error I am facing is related to the PUT request. Any assistance on resolving this problem would be greatly appreciated. Error: Argument passed in mus ...

Guide to creating standalone Express middleware that can interact with the raw request body

Can anyone help me with writing an Express middleware that can access the raw request body without affecting other handlers or middlewares? I want to achieve something like this: const middleware = [ express.raw({ type: '*/*' }), (req, res, n ...

Download files using ajax in express framework

Is there a way to initiate file download in response to an ajax post request without actually downloading the file? $(function(){ $('img.download').click(function() { var image_path = $(this).attr('class').split(" ")[1] $.aja ...

Translating Unicode characters to their corresponding ASCII values (SCRAPY)

I am currently utilizing Scrapy to scrape articles from a News Website and store them in mongoDB. However, upon insertion, I noticed there were unicode characters present in the MongoDB data like the following: "article": "Satya Nadella, Microsoft' ...

Pass the JSX data as JSON from the Express backend and showcase it as a component in the React frontend

I am currently developing a basic react front-end paired with an Express backend. Is it possible for me to have express send JSX data as JSON so that I can fetch it in react and utilize it as a component? Right now, I am sending JSON data and successfully ...