【问题标题】:CastError: Cast to ObjectId failed for value "ObjectId(610f16a6ba0d5fc2d4593093)"CastError:为值“ObjectId(610f16a6ba0d5fc2d4593093)”转换为 ObjectId 失败
【发布时间】:2022-01-23 20:23:19
【问题描述】:

我正在尝试使用“艺术家”的参考 ID 查询我的事件模型,以便我可以显示由给定艺术家主持的所有事件,但收到一个演员错误。下面的第四行是我如何尝试提取与给定艺术家相关的事件:

module.exports.showArtist = async (req, res,) => {
    const artist = await Artist.findById(req.params.id).populate('events');
    const artistId = "ObjectId(" + req.params.id + ")";
    const event = await Event.find( { "artist": artistId });
    if (!artist) {
        req.flash('error', 'Cannot find that Artist');
        return res.redirect('/artists');
    }
    res.render('artists/show', { artist });
}

我的代码顶部需要两个模型:

const Artist = require('../models/artist');
const Event = require('../models/event');

这是我的一个 mongodb 事件文档的外观 - 艺术家位于底部:

{ "_id" : ObjectId("6138c78e15832f41e263c601"), 
    "geometry" : 
        { "type" : "Point", 
          "coordinates" : [ -97.748541, 30.269936 ] 
         },
    "event_name" : "Friday night show", 
    "location" : "Austin, Tx 78745", 
    "description" : "Show at our Sam's Town Point", 
    "event_start" : ISODate("2021-09-11T03:00:00Z"), 
    "event_end" : ISODate("2021-09-11T04:25:00Z"), 
    "image" : "https://starbar.com", 
    "created" : ISODate("2021-09-08T14:24:14.399Z"), 
    "artist" : ObjectId("610f16a6ba0d5fc2d4593093"), 
    "__v" : 4, 
    "notification" : "30" 
}

这是完整的错误 - 我做错了什么?

CastError: Cast to ObjectId failed for value "ObjectId(610f16a6ba0d5fc2d4593093)" (type string) at path "artist" for model "Event"

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:
    module.exports.showArtist = async (req, res,) => {
    const artist = await Artist.findById(req.params.id).populate('events');
    const artistId = artist._id;
    const event = await Event.find( { "artist": artistId });
    if (!artist) {
        req.flash('error', 'Cannot find that Artist');
        return res.redirect('/artists');
    }
    res.render('artists/show', { artist });
    }
    

    当您使用 findById 时,您不需要重铸找到的 _id

    【讨论】:

    • 你我的朋友是个聪明人!!谢谢@Marco Bertelli
    猜你喜欢
    • 2020-08-25
    • 2021-06-27
    • 2021-03-14
    • 2021-09-05
    • 2014-06-20
    • 2016-05-06
    • 2019-01-06
    • 2016-11-11
    • 2017-03-26
    相关资源
    最近更新 更多