Skip to content

Saving embedded ObjectId as null #1427

@mikebarnhardt

Description

@mikebarnhardt

I have searched and tested for a solution to no avail.

I need to update the following document

DocumentSchema = new mongoose.Schema({
    title: String,
    content: String,
    related: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Document' }],
});

I use Document.findOne and then _.extends(doc, req.body) before doc.save() to update so that I can still use validation and middlewares. This method has worked fine with other documents until now.

Related is not required and if it is left empty I get the following error:

{ message: 'Cast to ObjectId failed for value "" at path "related"',
  name: 'CastError',
  type: 'ObjectId',
  value: [  ],
  path: 'related' }

I have tried

delete doc.related;
doc.related = null;
doc.related = [];
doc.set(related, null, Object);

And numerous other variations and still get the same error. I console.log(doc) everytime and most of the time the related field stays [] but even when it shows related: null it still won't save and gives me the same error.

So basically, the question is how do I save when the array of ObjectId's is null/empty?

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions