0

I am trying to delete a Record from MongoDB. My express code is like below

const deleteAddress = (req, res, next) => {
    var curid = req.params.id;
    curid = curid.replace(/\s/g, '');
    Address.findByIdAndRemove(curid)
      .then(result => {
        res.status(200).json({
          message: 'Address Deleted',
          result
        });
      })
      .catch(err => {
        console.log(err);
        res.status(500).json({
          message: 'Error Occured',
          error: err
        });
      });
}

I am getting error like below

{ CastError: Cast to ObjectId failed for value "undefined" at path "_id" for model "Address"
[0]     at new CastError (/home/foysal/Videos/my-app/node_modules/mongoose/lib/error/cast.js:29:11)
[0]     at ObjectId.cast (/home/foysal/Videos/my-app/node_modules/mongoose/lib/schema/objectid.js:242:11)
[0]     at ObjectId.SchemaType.applySetters (/home/foysal/Videos/my-app/node_modules/mongoose/lib/schematype.js:845:12)
[0]     at ObjectId.SchemaType._castForQuery (/home/foysal/Videos/my-app/node_modules/mongoose/lib/schematype.js:1248:15)
[0]     at ObjectId.SchemaType.castForQuery (/home/foysal/Videos/my-app/node_modules/mongoose/lib/schematype.js:1238:15)
[0]     at ObjectId.SchemaType.castForQueryWrapper (/home/foysal/Videos/my-app/node_modules/mongoose/lib/schematype.js:1217:15)
[0]     at cast (/home/foysal/Videos/my-app/node_modules/mongoose/lib/cast.js:307:32)
[0]     at model.Query.Query.cast (/home/foysal/Videos/my-app/node_modules/mongoose/lib/query.js:4340:12)
[0]     at castQuery (/home/foysal/Videos/my-app/node_modules/mongoose/lib/query.js:4192:18)
[0]     at model.Query.Query._findAndModify (/home/foysal/Videos/my-app/node_modules/mongoose/lib/query.js:3204:23)
[0]     at model.Query.<anonymous> (/home/foysal/Videos/my-app/node_modules/mongoose/lib/query.js:3165:8)
[0]     at model.Query._wrappedThunk [as _findOneAndRemove] (/home/foysal/Videos/my-app/node_modules/mongoose/lib/helpers/query/wrapThunk.js:16:8)
[0]     at process.nextTick (/home/foysal/Videos/my-app/node_modules/kareem/index.js:369:33)
[0]     at process._tickCallback (internal/process/next_tick.js:61:11)
[0]   message:
[0]    'Cast to ObjectId failed for value "undefined" at path "_id" for model "Address"',
[0]   name: 'CastError',
[0]   stringValue: '"undefined"',
[0]   kind: 'ObjectId',
[0]   value: 'undefined',
[0]   path: '_id',
[0]   reason: undefined,
[0]   model:
[0]    { [Function: model]
[0]      hooks: Kareem { _pres: [Map], _posts: [Map] },
[0]      base:
[0]       Mongoose {
[0]         connections: [Array],
[0]         models: [Object],
[0]         modelSchemas: [Object],
[0]         options: [Object],
[0]         _pluralize: [Function: pluralize],
[0]         Schema: [Function],
[0]         model: [Function],
[0]         plugins: [Array] },
[0]      modelName: 'Address',
[0]      model: [Function: model],
[0]      db:
[0]       NativeConnection {
[0]         base: [Mongoose],
[0]         collections: [Object],
[0]         models: [Object],
[0]         config: [Object],
[0]         replica: false,
[0]         options: null,
[0]         otherDbs: [],
[0]         relatedDbs: {},
[0]         states: [Object],
[0]         _readyState: 1,
[0]         _closeCalled: false,
[0]         _hasOpened: true,
[0]         '$internalEmitter': [EventEmitter],
[0]         _listening: false,
[0]         _connectionOptions: [Object],
[0]         name: 'addresses',
[0]         host: 'localhost',
[0]         port: 27017,
[0]         user: undefined,
[0]         pass: undefined,
[0]         client: [MongoClient],
[0]         '$initialConnection': [Promise],
[0]         _events: [Object],
[0]         _eventsCount: 2,
[0]         db: [Db] },
[0]      discriminators: undefined,
[0]      events:
[0]       EventEmitter { _events: {}, _eventsCount: 0, _maxListeners: undefined },
2
  • 1
    It looks like the curid you are passing is undefined, check it before passing it to mongo query. Commented Apr 7, 2019 at 3:26
  • 1
    Since you appear to have separated your "route handler" definition from the method, check that you are even passing id at all there. You should have something like route.delete('/yourpath/:id', deleteAddress) defined there. Without the :id the req.params.id will be undefined. Note also your request should be using a DELETE verb and including the id on the path. i.e DELETE /yourpath/5ca97bf60c3b7005121b2e21 Commented Apr 7, 2019 at 4:21

1 Answer 1

1

there can be two reason, as kgangadhar said you would have not getting the curid, second if you are getting the curid than you have pass as a ObjectId you would have getting a stringID

var ObjectId = Schema.ObjectId 

const deleteAddress = (req, res, next) => {
   var curid = new ObjectId(req.params.id);
   curid = curid.replace(/\s/g, '');
   Address.findByIdAndRemove(curid)
     .then(result => {
        res.status(200).json({
        message: 'Address Deleted',
        result
     });
   })
   .catch(err => {
      console.log(err);
      res.status(500).json({
      message: 'Error Occured',
      error: err
    });
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Mongoose actually automatically casts to ObjectId based on the schema defined with methods like findByIdAndRemove() ( and any other methods for that matter). The specific error actually says undefined as well, therefore manually casting would make no difference at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.