Search code examples
mongoosemongoose-schemaobjectid

Defining Mongoose model schema type as ObjectId with exception


I have the following task schema:

const taskSchema = new mongoose.Schema({
  description: {
    type: String,
    required: true,
    trim: true
  },
  folder: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Folder'
  },
  ...
}

When a user creates a task in the client, he can select to which folder this task belongs. Folders are also created with their own schema. However, when the user's folders are retrieved, in the client side I inject another default folder called 'All tasks' and it has an ID of 0. So if the user doesn't select a folder (which is OK), 0 is being passed as an ID. That's where I'm getting an error, since Mongoose can't cast 0 to an ObjectId.

"Task validation failed: folder: Cast to ObjectID failed for value \"0\" at path \"folder\""

Beside defining the folder type as String or Schema.Types.Mixed, are there any other possible solutions?


Solution

  • So I ended up altering the returned folders list on the server side instead of doing it on the client side.

    await req.user.populate({
        path: 'folders',
        match: {},
        options: {
          sort: {
            name: 1
          },
          collation: {
            locale: 'en'
          }
        }
      }).execPopulate()
      req.user.folders.unshift({
        _id: new mongoose.Types.ObjectId(),
        name: 'All tasks',
        owner: req.user._id
      })
      res.send(req.user.folders)
    

    Of course it required some alternation of the client side code, but now everything seems to be working as expected.