javascript - 什么情况下mongo会生成唯一ID

标签 javascript mongodb mongoose

假设我有一个具有以下格式的 Mongoose 模式:

experience: [
    {
      title: {
        type: String,
        required: true
      },
      company: {
        type: String,
        required: true
      },
      location: {
        type: String
      },
      from: {
        type: Date,
        required: true
      },
      to: {
        type: Date
      },
      current: {
        type: Boolean,
        default: false
      },
      description: {
        type: String
      }
    }
  ]

经验是一个存放对象的数组。现在我的问题是,传递给这个数组的对象是否有一个唯一的 ID?为什么会这样,它不是一个单独的模式,它只是数组中的一个对象。在什么情况下你会得到 生成一个唯一的 ID。

最佳答案

根据文档:mongoose

Mongoose has two distinct notions of subdocuments: arrays of subdocuments and single nested subdocuments. And each subdocument has an _id by default.

因此每次使用 pushcreate adding subdocs 创建子文档 都会导致为该子文档创建唯一的 _id

什么时候它不会为那些子文档生成那个_id?:

通过在子模式中显式定义 { _id : false } 。例如在这种情况下:

experience: [
    {
      _id: false,
      title: {
        type: String,
        required: true
      },
      company: {
        type: String,
        required: true
      },
      location: {
        type: String
      },
      from: {
        type: Date,
        required: true
      },
      to: {
        type: Date
      },
      current: {
        type: Boolean,
        default: false
      },
      description: {
        type: String
      }
    }
  ]

关于javascript - 什么情况下mongo会生成唯一ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58167023/

相关文章:

node.js - Express.js CRUD 应用程序无法删除

javascript - 使用 vueJS 有条件地设置 href 属性

MongoDB聚合: array of objects sum with group by

javascript - 在 MongoDB 中,当使用多个参数进行搜索时,如何知道哪个参数匹配

javascript - MongooseJS - 限制子文档中的文档数量

javascript - 删除一对一和一对多引用 - Mongoose

javascript - 在语句之间使用逗号安全吗?

javascript - 将占位符添加到 ng-grid

javascript - 制作更流畅的跳跃动画

mongodb - 可选在 .Find() MongoDB 查询中查找