强制转换错误:模型"Page"路径 "_id" 处的值"5be86bf8170c2c22f8bb93a6 "强制转换为对象 ID 失败



我正在用node/express/mongo/mongoose构建一个应用程序。我遇到了一个我似乎无法理解的错误,到目前为止,在谷歌上搜索也没有帮助。

我试图创建一个编辑页面,但遇到了一个错误。

Package.json

{
"name": "cmscart",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.3",
"connect-flash": "^0.1.1",
"ejs": "^2.6.1",
"express": "^4.16.4",
"express-messages": "^1.0.1",
"express-session": "^1.15.6",
"express-validator": "^5.3.0",
"mongoose": "^5.3.10"
}
}

edit_page.ejs

<%- include('../_layouts/adminheader')  %>
<h2 class="page-title">Edit a Page</h2>
<a href="/admin/pages" class="btn btn-primary">Back to all Pages</a>
<br>
<br>
<form method="post" action="/admin/pages/edit-page/<%= slug %> ">
<div class="form-group">
<label for="">Title</label>
<input type="text" name="title" value="<%= title %>" class="form-control" placeholder="Title">
</div>
<div class="form-group">
<label for="">Slug</label>
<input type="text" name="slug" value="<%= slug %>" class="form-control" placeholder="Slug">
</div>
<div class="form-group">
<label for="">Content</label>
<textarea name="content" class="form-control" placeholder="Content" rows="10" cols="30"><%= content %></textarea>
</div>
<input type="hidden" name="id" value="<%= id %> ">
<button class="btn btn-default">Submit</button>
</form>

<%- include('../_layouts/adminfooter')  %>

admin_pages.js

/* GET edit page*/
/*  here after edit page "/:slug" because we didn't have a fixed value of url*/
router.get('/edit-page/:slug', function (req, res) {
Page.findOne({ slug: req.params.slug }, function (err, page) {
if (err) return console.log(err);
res.render('admin/edit_page', {
title: page.title,
slug: page.slug,
content: page.content,
id: page._id
});
});

});


/* POST edit page*/

router.post('/edit-page/:slug', function (req, res) {
req.checkBody('title', 'Title must have a value').notEmpty();
req.checkBody('content', 'Content must have a value').notEmpty();
var title = req.body.title;
var slug = req.body.slug.replace(/s+/g, '-').toLowerCase();
if (slug == "") slug = title.replace(/s+/g, '-').toLowerCase();
var content = req.body.content;
var id = req.body.id;

var errors = req.validationErrors();
if (errors) {
res.render('admin/edit_page', {
errors: errors,
title: title,
slug: slug,
content: content,
id: id
});
} else {
Page.findOne({ slug: slug, _id: { '$ne': id } }, function (err, page) {
if (page) {
req.flash('danger', 'Page slug exists , choose another.');
res.render('admin/edit_page', {
title: title,
slug: slug,
content: content,
id:id
});
}
else {
Page.findByIdAndUpdate(id, function (err, page) {
if (err) {
return console.log(err);
}
page.title = title;
page.slug = slug;
page.content = content;

page.save(function (err) {
if (err)
return console.log(err);
req.flash('success', 'Page added!');
res.redirect('/admin/pages');
});
});
}
});
}

});

在这个我遇到了这个错误

CastError:模型"Page"的路径"_id"处的值"5be86bf8170c2c22f8bb93a6"转换为ObjectId失败在新的CastError(D:\projects\cmscart\node_modules\mongose\lib\error\cast.js:29:11)位于ObjectId.cast(D:\projects\cmscart\node_modules\mongoose\lib\schema\ObjectId.js:156:13)位于ObjectId.SchemaType.applySetters(D:\projects\cmscart\node_modules\mongoose\lib\schemateype.js:763:12)位于ObjectId.SchemaType_castForQuery(D:\projects\cmscart\node_modules\mongose\lib\schemateype.js:11166:15)位于ObjectId.SchemaType.castForQuery(D:\projects\cmscart\node_modules\mongoose\lib\schemateype.js:1156:15)位于ObjectId.SchemaType.castForQueryWrapper(D:\projects\cmscart\node_modules\mongoose\lib\schemateype.js:1135:15)at cast(D:\projects\cmscart\node_modules\mongose\lib\cast.js:306:32)at型号。Query.Query.cast(D:\projects\cmscart\node_modules\mongoose\lib\Query.js:4024:12)at型号。Query.Query_castConditions(D:\projects\cmscart\node_modules\mongose\lib\Query.js:1690:10)at型号。Query.Query_findOne(D:\projects\cmscart\node_modules\mongose\lib\Query.js:1926:8)在process.nextTick(D:\projects\cmscart\node_modules\kareem\index.js:369:33)在_combinedTickCallback(internal/process/next_tick.js:132:7)正在处理中_tickCallback(internal/process/next_tick.js:181:9)message:'模型"Page"的路径"_id"处的值"5be86bf8170c2c22f8bb93a6"转换为ObjectId失败',name:"CastError",字符串值:'"5be86bf8170c2c22f8bb93a6"',kind:"ObjectId",值:'5be86bf8170c2c22f8bb93a6',路径:"_id",原因:未定义,型号:{[函数:模型]钩子:Kareem{_pres:[Object],_posts:[Object]},基础:Mongoose{connections:[Array],模型:[对象],modelSchemas:[Object],选项:[对象],_复数形式:[函数:复数形式],plugins:[Array]},modelName:"页面",型号:[功能:型号],数据库:NativeConnection{base:[对象],集合:[Object],模型:[对象],config:[Object],副本:false,选项:null,其他Dbs:[],relatedDbs:{},states:[对象],_readyState:1,_closeCalled:false,_hasOpened:true,"$internalEmitter":[Object],_侦听:false,_connectionOptions:[对象],名称:"cmscart",host:'localhost',端口:27017,user:空,pass:null,客户端:[对象],"$initialConnection":[Object],_事件:[对象],_事件计数:1,db:[Object]},鉴别器:未定义,"$appliedMethods":true,"$appliedHooks":true,架构:架构{obj:[Object],路径:[对象],别名:{},子路径:{},virtuals:[对象],singleNestedPaths:{},嵌套:{},继承:{},callQueue:[],_索引:[],方法:{},methodOptions:{},statics:{},树:[对象],查询:{},childSchemas:[],插件:[Array],"$id":1,s: [对象],_userProvidedOptions:{},选项:[对象],"$globalPluginsApplied":true},集合:NativeCollection{集合:[Object],opts:[Object],name:"页面",collectionName:"pages",conn:[对象],队列:[],buffer:false,发射器:[Object]},查询:{[函数]基:[对象]},'$__insertMany':[函数],"$init":Promise{〔Circular〕},"$catch":true}}{CastError:模型"Page"的路径"_id"处的值"5be86bf8170c2c22f8bb93a6"转换为ObjectId失败在新的CastError(D:\projects\cmscart\node_modules\mongose\lib\error\cast.js:29:11)位于ObjectId.cast(D:\projects\cmscart\node_modules\mongoose\lib\schema\ObjectId.js:156:13)位于ObjectId.SchemaType.applySetters(D:\projects\cmscart\node_modules\mongoose\lib\schemateype.js:763:12)位于ObjectId.SchemaType_castForQuery(D:\projects\cmscart\node_modules\mongose\lib\schemateype.js:11166:15)位于ObjectId.SchemaType.castForQuery(D:\projects\cmscart\node_modules\mongoose\lib\schemateype.js:1156:15)位于ObjectId.SchemaType.castForQueryWrapper(D:\projects\cmscart\node_modules\mongoose\lib\schemateype.js:1135:15)at cast(D:\projects\cmscart\node_modules\mongose\lib\cast.js:306:32)at型号。Query.Query.cast(D:\projects\cmscart\node_modules\mongoose\lib\Query.js:4024:12)at型号。Query.Query_castConditions(D:\projects\cmscart\node_modules\mongose\lib\Query.js:1690:10)at型号。Query.Query_findOne(D:\projects\cmscart\node_modules\mongose\lib\Query.js:1926:8)在process.nextTick(D:\projects\cmscart\node_modules\kareem\index.js:369:33)在_combinedTickCallback(internal/process/next_tick.js:132:7)正在处理中_tickCallback(internal/process/next_tick.js:181:9)message:'模型"Page"的路径"_id"处的值"5be86bf8170c2c22f8bb93a6"转换为ObjectId失败',name:"CastError",字符串值:'"5be86bf8170c2c22f8bb93a6"',kind:"ObjectId",值:'5be86bf8170c2c22f8bb93a6',路径:"_id",原因:未定义,型号:{[函数:模型]钩子:Kareem{_pres:[Object],_posts:[Object]},基础:Mongoose{connections:[Array],模型:[对象],modelSchemas:[Object],选项:[对象],_复数形式:[函数:复数形式],plugins:[Array]},modelName:"页面",型号:[功能:型号],数据库:NativeConnection{base:[对象],集合:[Object],模型:[对象],config:[Object],副本:false,选项:null,其他Dbs:[],relatedDbs:{},states:[对象],_readyState:1,_closeCalled:false,_hasOpened:true,"$internalEmitter":[Object],_侦听:false,_connectionOptions:[对象],名称:"cmscart",host:'localhost',端口:27017,user:空,pass:null,客户端:[对象],"$initialConnection":[Object],_事件:[对象],_事件计数:1,db:[Object]},鉴别器:未定义,"$appliedMethods":true,"$appliedHooks":true,架构:架构{obj:[Object],路径:[对象],别名:{},子路径:{},virtuals:[对象],singleNestedPaths:{},嵌套:{},继承:{},callQueue:[],_索引:[],方法:{},methodOptions:{},statics:{},树:[对象],查询:{},childSchemas:[],插件:[Array],"$id":1,s: [对象],_userProvidedOptions:{},选项:[对象],"$globalPluginsApplied":true,_requiredpaths:[Array]},集合:NativeCollection{集合:[Object],opts:[Object],name:"页面",collectionName:"pages",conn:[对象],队列:[],buffer:false,发射器:[Object]},查询:{[函数]基:[对象]},'$__insertMany':[函数],"$init":Promise{〔Circular〕},"$catch":true}}{CastError:模型"Page"的路径"_id"处的值"5be86bf8170c2c22f8bb93a6"转换为ObjectId失败在新的CastError(D:\projects\cmscart\node_modules\mongose\lib\error\cast.js:29:11)位于ObjectId.cast(D:\projects\cmscart\node_modules\mongoose\lib\schema\ObjectId.js:156:13)位于ObjectId.SchemaType.applySetters(D:\projects\cmscart\node_modules\mongoose\lib\schemateype.js:763:12)位于ObjectId.SchemaType_castForQuery(D:\projects\cmscart\node_modules\mongose\lib\schemateype.js:11166:15)位于ObjectId.SchemaType.castForQuery(D:\projects\cmscart\node_modules\mongoose\lib\schemateype.js:1156:15)位于ObjectId.SchemaType.castForQueryWrapper(D:\projects\cmscart\node_modules\mongoose\lib\schemateype.js:1135:15)at cast(D:\projects\cmscart\node_modules\mongose\lib\cast.js:306:32)at型号。Query.Query.cast(D:\projects\cmscart\node_modules\mongoose\lib\Query.js:4024:12)at型号。Query.Query_castConditions(D:\projects\cmscart\node_modules\mongose\lib\Query.js:1690:10)at型号。Query.Query_findOne(D:\projects\cmscart\node_modules\mongose\lib\Query.js:1926:8)在process.nextTick(D:\projects\cmscart\node_modules\kareem\index.js:369:33)在_combinedTickCallback(internal/process/next_tick.js:132:7)正在处理中_tickCallback(internal/process/next_tick.js:181:9)message:'模型"Page"的路径"_id"处的值"5be86bf8170c2c22f8bb93a6"转换为ObjectId失败',name:"CastError",字符串值:'"5be86bf8170c2c22f8bb93a6"',kind:"ObjectId",值:'5be86bf8170c2c22f8bb93a6',路径:"_id",原因:未定义,型号:{[函数:模型]钩子:Kareem{_pres:[Object],_posts:[Object]},基础:Mongoose{connections:[Array],模型:[对象],modelSchemas:[Object],选项:[对象],_复数形式:[函数:复数形式],plugins:[Array]},modelName:"页面",型号:[功能:型号],数据库:NativeConnection{base:[对象],集合:[Object],模型:[对象],config:[Object],副本:false,选项:null,其他Dbs:[],relatedDbs:{},states:[对象],_readyState:1,_closeCalled:false,_hasOpened:true,"$internalEmitter":[Object],_侦听:false,_connectionOptions:[对象],名称:"cmscart",host:'localhost',端口:27017,user:空,pass:null,客户端:[对象],"$initialConnection":[Object],_事件:[对象],_事件计数:1,db:[Object]},鉴别器:未定义,"$appliedMethods":true,"$appliedHooks":true,架构:架构{obj:[Object],路径:[对象],别名:{},子路径:{},virtuals:[对象],singleNestedPaths:{},嵌套:{},继承:{},callQueue:[],_索引:[],方法:{},methodOptions:{},statics:{},树:[对象],查询:{},childSchemas:[],插件:[Array],"$id":1,s: [对象],_userProvidedOptions:{},选项:[对象],"$globalPluginsApplied":true,_requiredpaths:[Array]},集合:NativeCollection{集合:[Object],opts:[Object],name:"页面",collectionName:"pages",conn:[对象],队列:[],buffer:false,发射器:[Object]},查询:{[函数]基:[对象]},'$__insertMany':[函数],"$init":Promise{〔Circular〕},'$catch':true}}

"5be86bf8170c2c22f8bb93a6 "的末尾有一个空格字符。你试着先修剪一下吗?

在文件D:projectscmscartnode_moduleskareemindex.js的第369行中,使用id.trim()而不是id和您正在使用的任何位置,或者您可以首先在的开头更正id

最新更新