4

I have a simple document with name (require), description (optional). In my model, I update a document with a valid id and I pass description with value undefined because I want to remove this property from document. However, I got following error: message=Cast to string failed for value "undefined" at path "description", name=CastError, type=string, value=undefined, path=description . How do I remove description property on update when user does not provide description? Is it possible?

Thanks

/*jslint indent: 2, node: true, nomen: true*/

'use strict';

var Schema = require('mongoose').Schema;
var mongoose = require('mongoose');

var mongooser = require('../../lib/mongooser');

// Schema

var schema = new Schema({
  name: {
    required: true,
    set: mongooser.trimSetter,
    trim: true,
    type: String,
    unique: true
  },
  description: {
    set: mongooser.trimSetter,
    trim: true,
    type: String
  }
});

// Export

module.exports = mongoose.model('Role', schema);

// Role.js

var update = function (model, callback) {
    var test = { name: 'Users', description: undefined };

    RoleSchema.findByIdAndUpdate(model.id, test, function (error, role) {
      callback(error, role);
    });
};

2 Answers 2

2

If someone does not want to drop down to native driver, refer to this answer https://stackoverflow.com/a/54320056/5947136

The issue here is using type as a key in Schema.

var schema = new Schema({
 name: {
    required: true,
    set: mongooser.trimSetter,
    trim: true,
    type: String, // <-- This is causing the issue
    unique: true
  },
  description: {
    set: mongooser.trimSetter,
    trim: true,
    type: String // <-- This is causing the issue
  }
});

Refer the above answer for a solution without the need for native driver.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I can't believe I didn't see that. For or extra clarity, using type: String will force mongoose to try and cast the whole object into a string and fail.
1

Try dropping down to the native driver like so:

var update = function (model, callback) {
   RoleSchema.update({_id: model.id}, {$unset: {description: 1 }}, callback);
   });
};

2 Comments

is there anyway telling mongoose that here is my new data, update it using this so I don't have to set unset individual fields if they're missing? Thanks
You should have also described what is happening here instead of just dropping the piece of code . It could have helped more readers this way.

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.