What is the best way to retrieve a single document from MongoDB by using the URL ID parameter in JavaScript?

I'm currently working on a movie app project and have defined my movie Schema as follows:

const movieSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    genre: {
        type: String,
        required: true,
        lowercase: true,
        trim: true,
        enum: ['comedy', 'horor', 'romantic', 'action']
    }
});

const Movie = mongoose.model('Movie', movieSchema);

My goal is to retrieve a movie by its id, but the current implementation is not returning the desired result.

async function getMovie(id) {;
    return await Movie
        .find({"_id": {id}})
        .select('name genre')
}


router.get("/:id", async(req, res) => {
    try{
    const movie = await getMovie(req.params.id);
    if (!movie) return res.status(404).send("The genre with the given ID does not exist.");
    console.log(movie);
    res.send(movie);
    }
    catch(err){
        console.log("Error", err)
    }
});

There are two errors that I am encountering:

  1. Error CastError: Cast to ObjectId failed for value "{ id: '5f74c795cd1c5c22e82c18c6' }" at path "_id" for model "Movie"
  2. Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

I need assistance in rectifying these errors. Also, I am using Postman to test the API requests.

Answer №1

It would have been more efficient if I had utilized the findById method within the getMovie() function as shown below:

async function retrieveMovie(id) {;
    return await Movie
        .findById(id)
        .select('title genre')
}


router.get("/:id", async(req, res) => {
    try{
    const film = await retrieveMovie(req.params.id);
    console.log(film);
    res.send(film);
    }
    catch(error){
        console.log("An error occured", error)
    }
});

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

Issue: The initial parameter should be a File or Blob object

Hey there! I'm currently utilizing the compressorjs plugin for compressing images, but I'm encountering an issue when selecting images. You can find out more about the plugin here. Here is my code snippet: window.resolveLocalFileSystemURL( ...

Preserving variable scope in JavaScript even after defining a function

I am facing an issue with my JavaScript code that involves invoking a function within a function: var obj = { // returns the function with prevent default prepended. run: function(functor, context){ return function(e){ e.preventDefault(); ...

Password validation with Mongoose customization

I'm working on creating a Schema using mongoose, but I'm facing some challenges when it comes to implementing custom validation for the password. The password should meet the following criteria: It must contain at least one special character ...

React components multiplying with every click, tripling or even quadrupling in number

My app enables users to create channels/chatrooms for communication. I have implemented a feature where pressing a button triggers the creation of a channel, using the function: onCreateChannel. Upon calling this function, the state of createChannel chan ...

How to extract the parameters separated by slashes from a URL in Next.js

I need some guidance on how to redirect a URL in an express.js configuration. Here's the scenario: The URL is: profile/myname To forward to my page profile.js, I use the following code in my express.js config: server.get('/profile/:username&ap ...

Node development does not operate continuously

I'm facing a minor issue with node-dev. I followed the instructions in the readme file and successfully installed it. However, when I run the command like so: node-dev somescript.js, it only runs once as if I used regular node without -dev. It doesn&a ...

Sort firebase information by chronological order based on timestamp

I'm currently working on sorting track IDs from firebase based on their timestamp (createdAt). The function is functioning correctly, but the ordering doesn't seem to work as expected. I'm not sure where the issue lies. Any assistance or sug ...

Implementing dynamic option selection in Vue using JavaScript and v-model

Is there a way to manage the chosen value in a v-modeled select tag using vue.js? I created a jsFiddle demonstration, but unfortunately, it is not functioning correctly. This leads to my inquiry: vm.$set('selected', '1') // does not wo ...

Exploring the combined application of the AND and OR operators in JavaScript programming

{Object.keys(groupByMonthApplicants).map((obj,i) => <div key={obj} style={(i > 0 && (this.state.selectedTabId !== 'rejected' || this.state.selectedTabId !== 'approved')) ? {paddingTop:'15px',background:&a ...

What are the available search options in the MarkLogic Search API to limit keyword searches from including specified values within JSON properties?

Is there a way to limit the MarkLogic search API keyword search so it does not include specific JSON property values? For example, can I search for keyword 'x' in all properties of JSON documents except for those with values of 'p', &ap ...

Include CakePHP named parameters in the URL when selecting from a list

If I have a selection list like the one below: <select name='languages'> <option value='german'>German</option> <option value='english'>English</option> </select> How can I use Jav ...

Transferring Variables from WordPress PHP to JavaScript

I have implemented two WordPress plugins - Snippets for PHP code insertion and Scripts n Styles for JavaScript. My objective is to automatically populate a form with the email address of a logged-in user. Here is the PHP snippet used in Snippets: <?p ...

Contrasting the use of jQuery versus AJAX for updating static page text

While I haven't fully grasped the concept of AJAX yet, my understanding is that it can be beneficial for updating specific parts of a webpage. Does using AJAX only make sense when you require server interaction? I am looking to replace text on a webp ...

Update the URL and content in Django dynamically

When accessing a json response from my Django backend via the URL /inbox/<str:username>, all messages in the conversation with that user are retrieved. The issue arises on the inbox page, where both threads and chatbox are displayed together, similar ...

Experiencing the Pause: A Fresh Take on

I'm currently using this slideshow for a project, and I need to understand if it's possible to resume its interval. The current issue is that when you hover over the slideshow, the progress bar stops. But once you remove the mouse, it continues f ...

Exploring Angular's Implementation of D3 Force Simulation

Looking to incorporate a d3 force simulation in my Angular app. I have a run method that initializes and sets simulation options, as well as a ticked method that updates the simulation on each tick. However, I've encountered a few problems with this s ...

Determining the elapsed time using Momentjs

I need assistance with a NodeJS project where I am trying to determine if a specific amount of time (like 1 hour) has passed since creating an object. My project involves the use of MomentJS. For example, if moment(book.createdAt).fromNow() shows 2 hours ...

What is causing .then() to not wait for the promise to resolve?

I'm currently delving into an Angular project, and I must admit, it's all quite new to me. My confusion lies in the fact that the .then() function doesn't seem to be waiting for the promises to resolve. Could this have something to do with ...

Toggle Visibility of Div Based on Matching Class Name When Clicked

Just delving into the world of jQuery and could use some guidance. Is there a way to show a div with a matching class when a specific button is clicked? For example, clicking on a button with the class '.project1' should display the corresponding ...

Tips for optimizing Angular source code to render HTML for better SEO performance

Our web platform utilizes Angular JS for the front-end and node js for the backend, creating dynamic pages. When inspecting the code by viewing the source, it appears like this: For our business to succeed, our website needs to be SEO-friendly in order to ...