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

What is the method for automatically verifying elements within nested ng-repeats?

My div contains ng-repeat elements that are interconnected. Each ng-repeat element has checkboxes, and I want to automatically check the related elements in other ng-repeats when a top ng-repeat element is checked. Here is the actual representation of the ...

Can Nuxt's asyncData handle multiple requests with conditional statements?

I've been grappling with this issue for some time now. I understand how Nuxt asyncData can be used to make either one request or multiple requests, but is there a way to incorporate conditional logic for making multiple requests based on a query param ...

Guide on implementing a date selector for each button/option clicked using Vue.js

My experience with Vuejs is still fresh, and I've incorporated 3 buttons named chart1, chart2, and chart3. Whenever any of these buttons are clicked, I want a Date selection to appear in a radio type format. You can see an example below: https://i.ss ...

The function is not explicitly declared within the instance, yet it is being cited during the rendering process in a .vue

import PageNav from '@/components/PageNav.vue'; import PageFooter from '@/components/PageFooter.vue'; export default { name: 'Groups', components: { PageNav, PageFooter, }, data() { return { groups: ...

Execute identical task using a for loop in JavaScript

Here is a sample code snippet: var seats = [] for (a = 0; a <= seatsNumFront; a++) { seats.push(new Seat((a * xPad) + 300, 60, 30, 30, id++, "A", a, "#998515")) } for (b = 0; b <= seatsNumFront; b++) { seats.push(new Se ...

Employing res.sendStatus(200) in conjunction with JQuery AJAX

I've implemented a form that triggers an AJAX call to my backend, utilizing Node and Express. The onsubmit function is responsible for this interaction. Once the submission is successful, I use res.sendStatus(200) to inform the client. This results i ...

Is it possible to transfer a massive number of files using node.js?

I need to asynchronously copy a large number of files, about 25000 in total. I am currently using the library found at this link: https://github.com/stephenmathieson/node-cp. Below is the code snippet I am using: for(var i = 0; i < 25000; i++ ...

Incorporating additional ES6 modules during the development process

As I build a React component, I find that it relies on an ES6 component that I'm currently developing. Since I created the latter first, what is the typical method to include it during development as I work on the second component? If the dependency w ...

How to Mock a Mongoose model with Sinon

My current challenge involves stubbing the mongoose dependency being used in this object: var Page = function(db) { var mongoose = db || require('mongoose'); if(!this instanceof Page) { return new Page(db); } function ...

Having trouble iterating through an array of objects in Vue?

Having trouble looping through an array of objects in Vue3 <template> <div class="shadow-xl w-96 h-96 md:h-[600px] md:w-[600px] lg:my-12 lg:w-[700px] lg:h-[700px] rounded-md" > <button @click="getData">Get ...

Adjust the primary scrolling section of a webpage to halt once it reaches a specific distance from the bottom of the viewport

I am facing a situation where I need to ensure that when scrolling down, a fixed pink menu bar at the bottom of the page does not overlap with the main blue content. This can be achieved by treating the blue content as an iframe positioned 60px from the bo ...

What steps should be taken if my MongoDB document exceeds the size limit?

Is there a recommended course of action if my mongodb document becomes too extensive, causing the query to slow down significantly? click here for image description ...

Angular - Switching Displayed Information

I am currently working with Angular 4 and I am attempting to switch between contenteditable="true" and contenteditable="false" Here is what I have so far: <h1 (dblclick)="edit($event)" contentEditable="true">Double-click Here to edit</h1> Al ...

What sets Firebase apart from Express in terms of its core functionalities?

Currently, I am delving into the realm of writing an API using Express and MongoDB while incorporating Angular for routes and views. I have been contemplating whether Firebase and AngularFire could potentially eliminate the need for Express altogether, mak ...

Importing Angular libraries with the * symbol

One of the key modules in my library is sha256. To import it, I had to use the following syntax: import sha256 from 'sha256'; However, while researching this issue, I came across a question on Stack Overflow titled: Errors when using MomentJS ...

Retrieve information from a MongoDB document based on the specific month

If I have a user document with a createdAt field, how can I retrieve data by month in the condition? The format of the createdAt value is as follows: 2016-10-08T16:21:40.935Z Account.find({'what should be passed here?'}, function(err,response){ ...

Using parameters in Express.js/Node.js middleware

I am currently working on a nodeJS project where I need to pass parameters in middleware for validation purposes within the code. Here is an example of the middleware that I have created: 'use strict'; // eslint-disable-next-line no-unused-vars ...

Error: protractor encountered an unexpected issue

Currently, I am following this tutorial I went through all the steps mentioned in the tutorial except for what was suggested in this post instead of npm install -g protractor I opted for npm install -g protractor --no-optional So far, I have succe ...

Change background according to URL query

My goal is to dynamically change background images based on a URL parameter, specifically the destination code. With numerous background images available, it's crucial to display the correct one depending on the URL string. For instance, if the URL re ...

How can you style a two-item list in Material-UI React to display the items side by side?

I have a list that contains two items: 'label' and 'value'. This is the current layout: https://i.stack.imgur.com/HufX7.png How can I rearrange the items on the right to be positioned next to the label on the left? https://i.stack.im ...