【问题标题】:Mongoose adds _id to all nested objectsMongoose 为所有嵌套对象添加 _id
【发布时间】:2013-05-28 17:22:31
【问题描述】:

当创建包含嵌套对象的文档(例如对象数组)时,每个对象都有自己的 _id。例如,我的架构如下所示:

mongoose = require "mongoose"

Schema = mongoose.Schema

schema = new Schema
  name:
    type: String
    required: true
    unique: true
    trim: true

  lists: [
    list:
      type: Schema.Types.ObjectId
      required: true
      ref: "List"
    allocations: [
      allocation:
        type: Number
        required: true
    ]
  ]

  createdAt:
    type: Date
    default: Date.now

  updatedAt:
    type: Date

# Ensure virtual fields are serialised.
schema.set "toJSON",
  virtuals: true

exports = module.exports = mongoose.model "Portfolio", schema

当最终创建文档时,lists 数组中的每个对象都被赋予一个 _id,lists.allocations 数组中的每个 allocation 对象也是如此。这似乎有点矫枉过正并且使文档膨胀,但是 MongoDB(或 Mongoose)是否有理由需要文档来包含这些附加信息?如果没有,我想防止它发生,以便唯一的 _id 在根文档上。

此外,Mongoose 会自动为_id 创建一个虚拟的id,这是我需要的,因为我的客户端代码需要一个字段id。这就是为什么我使用 JSON 返回虚拟对象的原因。但是,由于整个文档中都有_id 字段,而不仅仅是在根目录,所以这个虚拟复制了它们中的所有。如果没有办法阻止额外的 _id 字段,我怎样才能获得一个仅适用于根文档 _id 的虚拟?或者,如果有更好的方法来做我想做的事情,那会是什么?

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    我已经找到了一种方法来使用相同的技术解决这两个问题:通过为每个嵌套对象类型使用显式模式并将它们的_idid 选项设置为false。似乎在嵌套您定义“内联”的对象时,Mongoose 会在幕后为每个对象创建模式。由于模式的默认值为_id: trueid: true,它们将获得_id 以及虚拟id。但是通过使用显式模式覆盖它,我可以控制_id 的创建。更多代码,但我得到了我想要的:

    mongoose = require "mongoose"
    
    Schema = mongoose.Schema
    
    AllocationSchema = new Schema
      allocation:
        type: Number
        required: true
    ,
      _id: false
       id: false
    
    mongoose.model "Allocation", AllocationSchema
    
    ListsSchema = new Schema
      list:
        type: Schema.Types.ObjectId
        required: true
        ref: "List"
      allocations: [AllocationSchema]
    ,
      _id: false
       id: false
    
    mongoose.model "Lists", ListsSchema
    
    PortfolioSchema = new Schema
      name:
        type: String
        required: true
        unique: true
        trim: true
    
      lists: [ListsSchema]
    
      createdAt:
        type: Date
        default: Date.now
    
      updatedAt:
        type: Date
    

    【讨论】:

    • 在版本 (3.6) 中,我可以简单地将 _id: false 添加到主架构中的子文档中,而无需制作单独的子架构
    • 如果您正在寻找 JavaScript 解决方案:stackoverflow.com/questions/17254008/…
    【解决方案2】:

    @neverfox 感谢您的信息,我只是添加了 Nodejs 的代码

    var _incidents = mongoose.Schema({
      name : {type : String},
      timestamp: {type : Number},
      _id : {id:false}
    });
    
    
    _schema = mongoose.Schema({
       _id: {type: String, required: true},
       user_id: {type: String, required: true}, 
       start_time: {type: Number, required: true},  
        incidents : [_incidents],
    });
    

    【讨论】:

    • 仅供参考,我可以在子文档中使用 false 而不是 {id:false} 作为 _id 的值
    猜你喜欢
    • 2018-12-22
    • 1970-01-01
    • 2017-10-03
    • 2013-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 2016-01-03
    相关资源
    最近更新 更多