Estoy tratando de consultar mi modelo de evento usando una ID de referencia para 'artista' para poder mostrar todos los eventos organizados por un artista determinado, pero recibo un error de transmisión. Mi cuarta línea a continuación es cómo intento obtener eventos asociados con un artista determinado:
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 }); }Se requieren ambos modelos en la parte superior de mi código:
const Artist = require('../models/artist'); const Event = require('../models/event');Así es como se ve uno de mis documentos de eventos mongodb: el artista está en la parte inferior:
{ "_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" }Aquí está el error completo: ¿qué estoy haciendo mal?
CastError: Cast to ObjectId failed for value "ObjectId(610f16a6ba0d5fc2d4593093)" (type string) at path "artist" for model "Event"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 }); }cuando usa un findById, no necesita volver a emitir un _id encontrado