2017-03-24 2 views
0

나는 간단한 포함 된 문서가 : 나는 몽고 쉘을 통해 작업 데이터를 쿼리 할 때몽구스 findOne 빈 배열 필드를 반환

{ 
    "username":"user001", 
    "name":"John", 
    "tasks":[ 
     {   
      "id":0, 
      "title":"Candy", 
      "description":"Lots of candy for you", 
      "category":"food", 
      "cost":2500, 
      "candyTypes":[ 
       {"name":"gum", "type":"sweet", "price":"2"}, 
       {"name":"chocolate", "type":"tasty", "price":"3"} 
      ] 
     } 
    ] 
} 

을, 내가 할 모든 :

db.users.findOne({ 'username': 'user001', 'tasks.id':4 }, {'tasks.$':1}) 

/* returns */ 

"tasks":[ 
    {   
     "id":0, 
     "title":"Candy", 
     "description":"Lots of candy for you", 
     "category":"food", 
     "cost":2500, 
     "candyTypes":[ 
      {"name":"gum", "type":"sweet", "price":"2"}, 
      {"name":"chocolate", "type":"tasty", "price":"3"} 
     ] 
    } 
] 

그러나 때 내가 몽구스에서 동일한 작업을 수행하려고하면 candyTypes 배열은 다시 빈 제공 :

Users.findOne({ 'username': username, 'tasks.id':taskId }, {'tasks.$':1}, function (err, data) { 
     console.log(data); 
}); 

/* returns */ 

"tasks":[ 
    {   
     "id":0, 
     "title":"Candy", 
     "description":"Lots of candy for you", 
     "category":"food", 
     "cost":2500, 
     "candyTypes":[] 
    } 
] 

나는 MongoDB를하고 아주 새로운 해요 몽구스.하지만 문서를 검색하고보고 난 후에, 나는 무엇이 실종되었는지 알 수 없다.

UPDATE

내가 몇 사용자가 요청, 그래서 여기 내 몽구스 스키마입니다 : 몽구스와

var UserSchema = new mongoose.Schema({ 
    username:String, 
    name:String, 
    tasks:[{ 
     id: Number, 
     title: String, 
     description:String, 
     category: String, 
     cost: Number, 
     candyTypes:[{ 
      title:String, 
      type:String, 
      value:String 
     }] 
    }] 
}); 
+0

스키마 정의를 표시 할 수 있습니까? – Veeram

+0

그냥 사용자 이름과 taskId를 콘솔로 만들려고합니다. mongo 쉘에 사용하는 것과 동일합니다 –

+0

예, 동일합니다. 사실 나는이 db 안에 하나의 테스트 사용자 만 가지고있다. –

답변

0

, 당신은 candyTypes 배열 채울 수 있습니다

Users.findOne({ 'username': username, 'tasks.id':taskId }, {'tasks.$':1}) 
.populate('candyTypes') 
.exec(function (err, data) { 
    console.log(data); 
}); 

참조를 문서 : http://mongoosejs.com/docs/populate.html

+0

하이 타일러, 도와 줘서 고마워. 이상하게도, 나는이 질문을 게시하기 바로 전에'populate()'를 사용해 보았지만 여전히 같은 결과를 얻었습니다. –

+0

나는 candyTypes가 실제로 작업 배열 내의 배열이기 때문에'.populate ('tasks.candyTypes') ' –

+0

'.populate ('tasks.candyTypes ')'를 시도했는데 오류가 발생했습니다. 그런 다음'.populate ('tasks. $.candyTypes ')'와 오류가 발생하지 않았지만 이전과 같은 결과가 나타납니다. –

0

나는 몽구스에서 특별한 의미를 가지고있는 type이라는 필드를 선언하는 것과 관련이 있다고 생각합니다. 즉, 필드의 유형을 나타내는 것입니다.

해당 필드의 이름을 다른 것으로 변경하면 (candyType) 더 잘 작동합니다.

또는 typeKey 옵션을 사용하여 몽구스가 다른 속성 이름을 사용하여 필드 유형을 나타낼 수 있습니다.

제쳐두고, 문서에는 price 필드가 있지만 스키마 이름은 value입니다.