Node.js CastError:value“的转换为ObjectId失败”&引用;在路径上“_id";对于“型号”;“董事”;
更新 我是Mongo和mongoose的新手,正在尝试用Director模型填充我的标题模式 当我向/titles发送GET请求时,我收到以下错误: CastError:对于模型“Director”的路径“\u id”处的值“”,转换为ObjectId失败 messageFormat:未定义, stringValue:“”“”, 种类:“ObjectId”, 值:“”, 路径:“\u id”, 原因:错误:传入的参数必须是12字节的单个字符串或24个十六进制字符的字符串 ValidationError:标题验证失败:控制器:路径“director”处的值“”的转换为ObjectId失败 我认为这是因为在很多情况下,数据集中的主管是“”。我想说的是,它不应该为director键为“”时创建id,但我还不知道如何做到这一点。有什么建议吗 我的代码:Node.js CastError:value“的转换为ObjectId失败”&引用;在路径上“_id";对于“型号”;“董事”;,node.js,mongodb,mongoose,mongoose-schema,mongoose-populate,Node.js,Mongodb,Mongoose,Mongoose Schema,Mongoose Populate,更新 我是Mongo和mongoose的新手,正在尝试用Director模型填充我的标题模式 当我向/titles发送GET请求时,我收到以下错误: CastError:对于模型“Director”的路径“\u id”处的值“”,转换为ObjectId失败 messageFormat:未定义, stringValue:“”“”, 种类:“ObjectId”, 值:“”, 路径:“\u id”, 原因:错误:传入的参数必须是12字节的单个字符串或24个十六进制字符的字符串 ValidationEr
const titlesSchema = new mongoose.Schema({
show_id: Number,
title: String,
director: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Director'
},
cast: String,
country: String,
date_added: String,
release_year: Number,
rating: String,
duration: String,
listed_in: String,
description: String,
type: String
})
const Title = mongoose.model('Title', titlesSchema)
const Director = mongoose.model('Director', {
name: String
})
// return all titles:
app.get('/titles', async (req, res) => {
const titles = await Title.find().populate('director')
res.json(titles)
})
查看您在
director
字段中传递的id。我想这就是错误所在。您能否确认存储在该字段中的字符串是有效的mongoose id?