我正在嘗試使用“藝術家”的參考 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"
uj5u.com熱心網友回復:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/390879.html
標籤:javascript 节点.js MongoDB 猫鼬
上一篇:重命名檔案沒有正確的指定名稱
