我有一个简单的用户模型,它有一个名为bio的属性,如下所示:
const userSchema = new mongoose.Schema{
bio:{
type: String,
max: 150,
default: "Welcome to my linktree!"
}
}我有一个编辑bio的函数,如下所示:
exports.editBio = async (req, res) => {
User.findByIdAndUpdate({_id: req.user._id}, {bio: req.body}, (err,data) => {
if(err){
res.json(err)
}else{
res.json(`Bio updated`)
}
})
}但是,我一直收到错误:
{
"stringValue": "\"bio\"",
"valueType": "string",
"kind": "ObjectId",
"value": "bio",
"path": "_id",
"reason": {},
"name": "CastError",
"message": "Cast to ObjectId failed for value \"bio\" (type string) at path \"_id\" for model \"User\""
}我怎么才能解决这个问题?
发布于 2021-10-16 20:50:09
这是我问题的答案:-
路线的顺序以前是:
router.put('/:id/edit/:linkId', isLoggedIn, isAuthenticated, editLink)
router.put('/:id/edit/bio', isLoggedIn, isAuthenticated, editBio)我第一次改变了这些路线的顺序(在互联网上搜索了一些类似的问题之后,这似乎奏效了)。路线新秩序:
router.put('/:id/edit/bio', isLoggedIn, isAuthenticated, editBio)
router.put('/:id/edit/:linkId', isLoggedIn, isAuthenticated, editLink)然后我编辑了我的editBio函数(下面写的代码):
exports.editBio = async (req, res) => {
var input = JSON.stringify(req.body);
var fields = input.split('"');
var newBio = fields[3];
if(newBio.length > 150){
return res.json(`Bio cannot be more than 150 characters`)
}else{
try {
await User.findByIdAndUpdate(req.user._id, { bio: newBio });
res.json(`Bio updated`)
}catch (err) {
res.json(err)
}
}
}https://stackoverflow.com/questions/69594355
复制相似问题