将 Mongoose 模型模式类型定义为 ObjectId,但有异常

Defining Mongoose model schema type as ObjectId with exception

我有以下任务架构:

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

当用户在客户端创建任务时,他可以select这个任务属于哪个文件夹。文件夹也是用它们自己的架构创建的。但是,当检索到用户的文件夹时,在客户端我注入了另一个名为 'All tasks' 的默认文件夹,它的 ID 为 0。因此,如果用户没有 select 文件夹(这没关系), 0 作为 ID 传递。这就是我遇到错误的地方,因为 Mongoose 无法将 0 转换为 ObjectId。

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

除了将文件夹类型定义为 String 或 Schema.Types.Mixed,还有其他可能的解决方案吗?

所以我最终在服务器端更改了返回的文件夹列表,而不是在客户端。

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)

当然,它需要对客户端代码进行一些改动,但现在一切似乎都按预期工作。