如何使用javascript从MongoDB获取一个ID为URL的文档

如何使用javascript从MongoDB获取一个ID为URL的文档,javascript,mongodb,express,mongoose,Javascript,Mongodb,Express,Mongoose,我正在制作一个基本的电影应用程序项目,我的电影模式如下所示: const movieSchema = new mongoose.Schema({ name: { type: String, required: true }, genre: { type: String, required: true, lowercase: true, trim: true, e

我正在制作一个基本的电影应用程序项目,我的电影模式如下所示:

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);
async function getMovie(id) {;
    return await Movie
        .findById(id)
        .select('name genre')
}


router.get("/:id", async(req, res) => {
    try{
    const movie = await getMovie(req.params.id);
    console.log(movie);
    res.send(movie);
    }
    catch(err){
        console.log("Error", err)
    }
});
我试着用身份证拍一部电影,但这样不行

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)
    }
});
我有两个错误:

  • 错误CastError:对值“{id: “电影”模型的路径“\u id”处的“5f74c795cd1c5c22e82c18c6”}
  • 错误:传入的参数必须是12字节的单个字符串或 由24个十六进制字符组成的字符串
  • 我应该如何正确地编写此代码?
    顺便说一句,使用postman检查请求

    我应该在getMovie()函数中使用findById方法,如下所示:

    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);
    
    async function getMovie(id) {;
        return await Movie
            .findById(id)
            .select('name genre')
    }
    
    
    router.get("/:id", async(req, res) => {
        try{
        const movie = await getMovie(req.params.id);
        console.log(movie);
        res.send(movie);
        }
        catch(err){
            console.log("Error", err)
        }
    });
    

    您发送的请求如何?