2013-06-02 34 views
15

使用嵌套对象(例如对象数组)创建文档时,每个对象都有自己的_id。例如,我的模式是这样的:Mongoose将_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,因为是每个allocation对象lists.allocations数组中,最终被创建的文档时。这似乎是矫枉过正和膨胀的文件,但是有没有一个原因MongoDB(或Mongoose)需要该文件包含这些额外的信息?如果没有,我想阻止它发生,以便唯一的_id位于根文档中。

此外,猫鼬会自动创建一个虚拟id_id,这是我需要的,因为我的客户端代码期望一个场id。这就是为什么我使用JSON返回虚拟。但是,因为在整个文档中都有_id字段,而不仅仅是根,所以这个虚拟字段重复了全部。如果没有办法阻止额外的_id字段,我怎样才能得到一个虚拟只适用于根文档_id?或者如果有更好的方法去做我想要做的事情,它会是什么?

回答

11

我已经找到了解决这两个问题的方法:通过为每个嵌套对象类型使用显式模式并将它们的_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 
+11

在版本(3.6),我能够简单地添加_id:假到主模式中的subdoc,而不需要制作单独的子模式 – cyberwombat

+1

如果您正在寻找JavaScript解决方案:http://stackoverflow.com/questions/17254008/stop-mongoose-from-created-ids-for- subdocument-arrays –

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], 
}); 
+0

仅供参考我能够使用false而不是{id:false}作为子文档中_id的值 –

相关问题