我有一个简单的用户模型有一个属性叫做bio如下:
const userSchema = new mongoose.Schema{
bio:{
type: String,
max: 150,
default: "Welcome to my linktree!"
}
}
我有一个函数编辑生物如下:
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""
}
我该如何解决这个问题?
这就是我的问题的答案:-
之前的路由顺序是:
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)
}
}
}