2017-02-27 4 views
1

모든 하위 문서에 ObjectId가를 작성하지 :몽구스 자체 참조 스키마는 다음과 같이, 내가 자기 참조 필드가 몽구스의 스키마를

var mongoose = require('mongoose'); 

var CollectPointSchema = new mongoose.Schema({ 
    name: {type: String}, 
    collectPoints: [ this ] 
}); 

CollectPoint 객체가 삽입 될 때 :

{ 
    "name": "Level 1" 
} 

괜찮아, 결과는 같은 것으로 예상된다 :

{ 
    "_id": "58b36c83b7134680367b2547", 
    "name": "Level 1", 
    "collectPoints": [] 
} 

을하지만 자기 참조 서브 다큐를 삽입 할 때 아이 CollectPointSchema_id 어디

{ 
    "_id": "58b36c83b7134680367b2547", 
    "name": "Level 1", 
    "collectPoints": [{ 
    "name": "Level 1.1" 
    }] 
} 

: ments는

{ 
    "name": "Level 1", 
    "collectPoints": [{ 
    "name": "Level 1.1" 
    }] 
} 

이것이 나에게 준다? 이건 _id이 필요합니다. 임베디드 CollectPoint 항목을 선언 할 때

+0

[이 재귀 함수] (https://gist.github.com/GSchutz/100358d4a614b563da29e72c5f8cd5e9)로이 문제를 해결합니다. – Guilherme

답변

1

당신은 새로운 객체를 구축해야합니다

var data = new CollectPoint({ 
    name: "Level 1", 
    collectPoints: [ 
     new CollectPoint({ 
      name: "Level 1.1", 
      collectPoints: [] 
     }) 
    ] 
}); 

이 식으로 _idcollectPoints 달리, 당신은 그냥 평범한 된 JSONObject를 만들 CollectPoint의 instanciation에 의해 생성됩니다.

var data = new CollectPoint({ 
    name: "Level 1", 
    collectPoints: [{ 
     name: "Level 1.1", 
     collectPoints: [] 
    }] 
}); 
: 다음과 같은 오류를 트리거

var CollectPointSchema = new mongoose.Schema({ 
    name: { type: String }, 
    collectPoints: { 
     type: [this], 
     validate: { 
      validator: function(v) { 
       if (!Array.isArray(v)) return false 
       for (var i = 0; i < v.length; i++) { 
        if (!(v[i] instanceof CollectPoint)) { 
         return false; 
        } 
       } 
       return true; 
      }, 
      message: 'bad collect point format' 
     } 
    } 
}); 

이 방법 :

은 해당 항목이 잘못된 유형이있는 경우 오류를 트리거하여 배열의 validator를 구축, 문제의 그 종류를 피하려면
+0

고마워요, 당신의 대답은 내가 생각하지 않은 몽구스의 기본 개념을 없앴습니다. 그러나 나는'collectPoints : [this]'를 추가 할 때'new ..()'를 강제해야하거나, 아마도이 관계가 모델에 있어야한다고 생각합니다. (미안, 그냥 여기로 나눠서) – Guilherme