首页 文章

Mongoose将_id添加到所有嵌套对象

提问于
浏览
16

在创建具有嵌套对象(例如,对象数组)的文档时,每个对象都有自己的_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 对象都被赋予.id . 这似乎有点过分并使文档膨胀,但MongoDB(或Mongoose)是否需要该文档来包含这些附加信息?如果没有,我想阻止它发生,以便唯一的_id在根文档上 .

此外,Mongoose会自动为 _id 创建一个虚拟 id ,这是我需要的,因为我的客户端代码需要一个字段 id . 这就是我使用JSON返回虚拟的原因 . 但是,因为整个文档中都有 _id 个字段,而不仅仅是根目录,所以这个虚拟副本全部复制 . 如果无法阻止其他_id字段,如何才能使虚拟仅应用于根文档_id?或者,如果有更好的方法来做我正在尝试做的事情,它会是什么?

2 回答

  • 14

    我已经想出了一种方法,可以用相同的技术解决这两个问题:为每个嵌套对象类型使用显式模式,并将 _idid 选项设置为 false . 似乎在嵌套定义"inline"的对象时,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
    
  • 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],
    });
    

相关问题