2013-06-02 2 views
15

중첩 된 객체 (예 : 객체의 배열)로 문서를 만들 때 각 객체에는 자체 _id가 지정됩니다. 예를 들어, 내 스키마는 다음과 같습니다 다음 lists.allocations 배열의 모든 allocation 객체이기 때문에 문서를 최종적으로 생성 될 때몽구스가 모든 중첩 된 객체에 _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 주어집니다. 이것은 잔인한 것 같아서 문서를 부풀게하지만 MongoDB (또는 몽구스)가이 추가 정보를 담고있는 문서를 필요로하는 이유가 있습니까? 그렇지 않다면, _id가 루트 문서에 있도록 그 일이 발생하지 않도록하고 싶습니다.

또한 클라이언트 코드에 id 필드가 필요하기 때문에 Mongoose는 _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를 추가 할 수 있어요에 대한 코드를 추가 : 거짓 별도의 하위 스키마를 만들 필요없이 기본 스키마의 하위 문서 오른쪽으로 – 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

FYI 하위 문서의 _id 값에 {id : false} 대신 단지 false를 사용할 수있었습니다. –

관련 문제