Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: CastError: Cast to embedded failed for value "{ value: 'x' }" at path "items"

After updating to Mongoose 5.11.13 I am getting the following error when trying to add an item to a sub-object inside a document.

CastError: Cast to embedded failed for value "{ value: 'new item' }" at path "items"
    at model.Query.exec (D:\repos\pushbox\node_modules\mongoose\lib\query.js:4358:21)
    at model.Query.Query.then (D:\repos\pushbox\node_modules\mongoose\lib\query.js:4452:15)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  messageFormat: undefined,
  stringValue: `"{ value: 'new item' }"`,
  kind: 'embedded',
  value: "{ value: 'new item' }",
  path: 'items',
  reason: TypeError: this.ownerDocument(...).isSelected is not a function

My main Schma is called Card. It holds a sub-object/sub-document called Property and it looks like this:

export const CardSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },

  description: {
    type: String,
    default: '',
  },

  // Checklists in a Card
  checklists: [{
    title: {
      type: String,
      required: true,
    },
    items: [{
      name: String,
      select: Boolean,
    }],
  }],
 // Properties in a card
  properties: [{
    name: {
      type: String,
      required: true,
    },
    items: [{
      value: { type: String, default: '' },
      isSelected: { type: Boolean, default: false },
    }],
  }],

  box: {
    type: ObjectId,
    ref: 'Box',
  },
}, {
  timestamps: { createdAt: true, updatedAt: true },
});

The query being used to insert a new item inside a property is:

const newPropItem = await Card.findOneAndUpdate(
        {
          _id: cardId,
          'properties._id': propertyId,
        },
        {
          $push: {
            'properties.$.items': { value: newItem.trim() },
          },
        },
        {
          new: true,
        },
      );

I have no idea why this is happening as we have a similar query for Checklist and it works. I tried this query inside the mongo shell and it worked there. Could you guys help me figure out what exactly am I missing?

Oh and I tried looking into the whole TypeError: this.ownerDocument(...).isSelected is not a function part as well, didnt have any luck finding anything that could help me in my case

like image 547
Edd Chang Avatar asked Nov 06 '22 03:11

Edd Chang


1 Answers

you can not using isSelected in Schema as a field name because isSelected() internally for checking which paths we need to validate in mongoose,so change filed name to isSelect or ...

like image 90
Mohammad Yaser Ahmadi Avatar answered Nov 11 '22 06:11

Mohammad Yaser Ahmadi