2
votes

I'm building an app with node/express/mongo/mongoose. I've encountered an error that I can't seem to figure out and googling around has so far not been helpful.

I've tried to create an edit page and I'd encountered an error.

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');

                    });
                });
            }
        });
    }


});

In this i've encountered this error

CastError: Cast to ObjectId failed for value "5be86bf8170c2c22f8bb93a6 " at path "_id" for model "Page" at new CastError (D:\projects\cmscart\node_modules\mongoose\lib\error\cast.js:29:11) at ObjectId.cast (D:\projects\cmscart\node_modules\mongoose\lib\schema\objectid.js:156:13) at ObjectId.SchemaType.applySetters (D:\projects\cmscart\node_modules\mongoose\lib\schematype.js:763:12) at ObjectId.SchemaType._castForQuery (D:\projects\cmscart\node_modules\mongoose\lib\schematype.js:1166:15) at ObjectId.SchemaType.castForQuery (D:\projects\cmscart\node_modules\mongoose\lib\schematype.js:1156:15) at ObjectId.SchemaType.castForQueryWrapper (D:\projects\cmscart\node_modules\mongoose\lib\schematype.js:1135:15) at cast (D:\projects\cmscart\node_modules\mongoose\lib\cast.js:306:32) at model.Query.Query.cast (D:\projects\cmscart\node_modules\mongoose\lib\query.js:4024:12) at model.Query.Query._castConditions (D:\projects\cmscart\node_modules\mongoose\lib\query.js:1690:10) at model.Query.Query._findOne (D:\projects\cmscart\node_modules\mongoose\lib\query.js:1926:8) at process.nextTick (D:\projects\cmscart\node_modules\kareem\index.js:369:33) at _combinedTickCallback (internal/process/next_tick.js:132:7) at process._tickCallback (internal/process/next_tick.js:181:9) message: 'Cast to ObjectId failed for value "5be86bf8170c2c22f8bb93a6 " at path "_id" for model "Page"', name: 'CastError', stringValue: '"5be86bf8170c2c22f8bb93a6 "', kind: 'ObjectId', value: '5be86bf8170c2c22f8bb93a6 ', path: '_id', reason: undefined, model: { [Function: model] hooks: Kareem { _pres: [Object], _posts: [Object] }, base: Mongoose { connections: [Array], models: [Object], modelSchemas: [Object], options: [Object], _pluralize: [Function: pluralize], plugins: [Array] }, modelName: 'Page', model: [Function: model], db: NativeConnection { base: [Object], collections: [Object], models: [Object], config: [Object], replica: false, options: null, otherDbs: [], relatedDbs: {}, states: [Object], _readyState: 1, _closeCalled: false, _hasOpened: true, '$internalEmitter': [Object], _listening: false, _connectionOptions: [Object], name: 'cmscart', host: 'localhost', port: 27017, user: null, pass: null, client: [Object], '$initialConnection': [Object], _events: [Object], _eventsCount: 1, db: [Object] }, discriminators: undefined, '$appliedMethods': true, '$appliedHooks': true, schema: Schema { obj: [Object], paths: [Object], aliases: {}, subpaths: {}, virtuals: [Object], singleNestedPaths: {}, nested: {}, inherits: {}, callQueue: [], _indexes: [], methods: {}, methodOptions: {}, statics: {}, tree: [Object], query: {}, childSchemas: [], plugins: [Array], '$id': 1, s: [Object], _userProvidedOptions: {}, options: [Object], '$globalPluginsApplied': true }, collection: NativeCollection { collection: [Object], opts: [Object], name: 'pages', collectionName: 'pages', conn: [Object], queue: [], buffer: false, emitter: [Object] }, Query: { [Function] base: [Object] }, '$__insertMany': [Function], '$init': Promise { [Circular] }, '$caught': true } } { CastError: Cast to ObjectId failed for value "5be86bf8170c2c22f8bb93a6 " at path "_id" for model "Page" at new CastError (D:\projects\cmscart\node_modules\mongoose\lib\error\cast.js:29:11) at ObjectId.cast (D:\projects\cmscart\node_modules\mongoose\lib\schema\objectid.js:156:13) at ObjectId.SchemaType.applySetters (D:\projects\cmscart\node_modules\mongoose\lib\schematype.js:763:12) at ObjectId.SchemaType._castForQuery (D:\projects\cmscart\node_modules\mongoose\lib\schematype.js:1166:15) at ObjectId.SchemaType.castForQuery (D:\projects\cmscart\node_modules\mongoose\lib\schematype.js:1156:15) at ObjectId.SchemaType.castForQueryWrapper (D:\projects\cmscart\node_modules\mongoose\lib\schematype.js:1135:15) at cast (D:\projects\cmscart\node_modules\mongoose\lib\cast.js:306:32) at model.Query.Query.cast (D:\projects\cmscart\node_modules\mongoose\lib\query.js:4024:12) at model.Query.Query._castConditions (D:\projects\cmscart\node_modules\mongoose\lib\query.js:1690:10) at model.Query.Query._findOne (D:\projects\cmscart\node_modules\mongoose\lib\query.js:1926:8) at process.nextTick (D:\projects\cmscart\node_modules\kareem\index.js:369:33) at _combinedTickCallback (internal/process/next_tick.js:132:7) at process._tickCallback (internal/process/next_tick.js:181:9) message: 'Cast to ObjectId failed for value "5be86bf8170c2c22f8bb93a6 " at path "_id" for model "Page"', name: 'CastError', stringValue: '"5be86bf8170c2c22f8bb93a6 "', kind: 'ObjectId', value: '5be86bf8170c2c22f8bb93a6 ', path: '_id', reason: undefined, model: { [Function: model] hooks: Kareem { _pres: [Object], _posts: [Object] }, base: Mongoose { connections: [Array], models: [Object], modelSchemas: [Object], options: [Object], _pluralize: [Function: pluralize], plugins: [Array] }, modelName: 'Page', model: [Function: model], db: NativeConnection { base: [Object], collections: [Object], models: [Object], config: [Object], replica: false, options: null, otherDbs: [], relatedDbs: {}, states: [Object], _readyState: 1, _closeCalled: false, _hasOpened: true, '$internalEmitter': [Object], _listening: false, _connectionOptions: [Object], name: 'cmscart', host: 'localhost', port: 27017, user: null, pass: null, client: [Object], '$initialConnection': [Object], _events: [Object], _eventsCount: 1, db: [Object] }, discriminators: undefined, '$appliedMethods': true, '$appliedHooks': true, schema: Schema { obj: [Object], paths: [Object], aliases: {}, subpaths: {}, virtuals: [Object], singleNestedPaths: {}, nested: {}, inherits: {}, callQueue: [], _indexes: [], methods: {}, methodOptions: {}, statics: {}, tree: [Object], query: {}, childSchemas: [], plugins: [Array], '$id': 1, s: [Object], _userProvidedOptions: {}, options: [Object], '$globalPluginsApplied': true, _requiredpaths: [Array] }, collection: NativeCollection { collection: [Object], opts: [Object], name: 'pages', collectionName: 'pages', conn: [Object], queue: [], buffer: false, emitter: [Object] }, Query: { [Function] base: [Object] }, '$__insertMany': [Function], '$init': Promise { [Circular] }, '$caught': true } } { CastError: Cast to ObjectId failed for value "5be86bf8170c2c22f8bb93a6 " at path "_id" for model "Page" at new CastError (D:\projects\cmscart\node_modules\mongoose\lib\error\cast.js:29:11) at ObjectId.cast (D:\projects\cmscart\node_modules\mongoose\lib\schema\objectid.js:156:13) at ObjectId.SchemaType.applySetters (D:\projects\cmscart\node_modules\mongoose\lib\schematype.js:763:12) at ObjectId.SchemaType._castForQuery (D:\projects\cmscart\node_modules\mongoose\lib\schematype.js:1166:15) at ObjectId.SchemaType.castForQuery (D:\projects\cmscart\node_modules\mongoose\lib\schematype.js:1156:15) at ObjectId.SchemaType.castForQueryWrapper (D:\projects\cmscart\node_modules\mongoose\lib\schematype.js:1135:15) at cast (D:\projects\cmscart\node_modules\mongoose\lib\cast.js:306:32) at model.Query.Query.cast (D:\projects\cmscart\node_modules\mongoose\lib\query.js:4024:12) at model.Query.Query._castConditions (D:\projects\cmscart\node_modules\mongoose\lib\query.js:1690:10) at model.Query.Query._findOne (D:\projects\cmscart\node_modules\mongoose\lib\query.js:1926:8) at process.nextTick (D:\projects\cmscart\node_modules\kareem\index.js:369:33) at _combinedTickCallback (internal/process/next_tick.js:132:7) at process._tickCallback (internal/process/next_tick.js:181:9) message: 'Cast to ObjectId failed for value "5be86bf8170c2c22f8bb93a6 " at path "_id" for model "Page"', name: 'CastError', stringValue: '"5be86bf8170c2c22f8bb93a6 "', kind: 'ObjectId', value: '5be86bf8170c2c22f8bb93a6 ', path: '_id', reason: undefined, model: { [Function: model] hooks: Kareem { _pres: [Object], _posts: [Object] }, base: Mongoose { connections: [Array], models: [Object], modelSchemas: [Object], options: [Object], _pluralize: [Function: pluralize], plugins: [Array] }, modelName: 'Page', model: [Function: model], db: NativeConnection { base: [Object], collections: [Object], models: [Object], config: [Object], replica: false, options: null, otherDbs: [], relatedDbs: {}, states: [Object], _readyState: 1, _closeCalled: false, _hasOpened: true, '$internalEmitter': [Object], _listening: false, _connectionOptions: [Object], name: 'cmscart', host: 'localhost', port: 27017, user: null, pass: null, client: [Object], '$initialConnection': [Object], _events: [Object], _eventsCount: 1, db: [Object] }, discriminators: undefined, '$appliedMethods': true, '$appliedHooks': true, schema: Schema { obj: [Object], paths: [Object], aliases: {}, subpaths: {}, virtuals: [Object], singleNestedPaths: {}, nested: {}, inherits: {}, callQueue: [], _indexes: [], methods: {}, methodOptions: {}, statics: {}, tree: [Object], query: {}, childSchemas: [], plugins: [Array], '$id': 1, s: [Object], _userProvidedOptions: {}, options: [Object], '$globalPluginsApplied': true, _requiredpaths: [Array] }, collection: NativeCollection { collection: [Object], opts: [Object], name: 'pages', collectionName: 'pages', conn: [Object], queue: [], buffer: false, emitter: [Object] }, Query: { [Function] base: [Object] }, '$__insertMany': [Function], '$init': Promise { [Circular] }, '$caught': true } }

1

1 Answers

0
votes

There is an space character at the end of "5be86bf8170c2c22f8bb93a6 ". Do you try trim it first?

in file D:\projects\cmscart\node_modules\kareem\index.js line 369 use id.trim() instead of id and any where you are using, or you can first correct the id at the beginning