2014-05-23 3 views
-1

에 포함 된 문서를 만들 :다음과 같이 내가 스키마를 설정하거나 몽구스

나는 주어진 poll_id 및 설문 조사에 응답 한 사람의 OWNER_ID에 대한 대답을 설정하는 방법
/** 
* Answer Schema 
*/ 
var AnswerSchema = new Schema({ 
    answer: Number, 
    owner_id: Schema.Types.ObjectId 
}); 

/** 
* Poll Schema 
*/ 
var PollSchema = new Schema({ 
    question: { type: String, required: true, trim: true }, 
    choices: [ { type: String, required: true, trim: true} ], 
    answers: [AnswerSchema] 
}); 

?

답변

0

"설정 또는 생성"이라는 용어는 약간 위로 열립니다. 당신이 .find() 후 현재 문서를 일단

은 기본적으로 당신은 표준 자바 스크립트 배열 푸시와 달리 .update()으로 $push 연산자를 사용하여 배열에 (생성) 새 항목을 추가하거나 것입니다.

그러나 주어진 소유자에 대한 기존 답변을 "업데이트"하고 싶다면 2 단계 작업 일 수 있습니다. 그렇지 않다면 $push을 사용하여 "업데이트"를 원할 것입니다. 당신이 "소유자"당 하나 이상의 답을 가지고 걱정하지 않는 경우

PollSchema.update(
    { "_id": poll_id, "answers.owner_id": owner_id } 
    { "$set":{ "answers.answer": value } }, 
    function(err,numAffected) { 

     if (err) 
      throw err;  // or whatever handling 

     // If this didn't modify anything then $push a document 
     if (numAffected != 0) { 
      PollSchema.update(
       { "_id": poll_id }, 
       { "$push": { 
        "answers": { 
         "owner_id": owner_id, 
         "answer": value 
        } 
       }}, 
       function(err, numAffected) { 
        // more things in here 
       } 
      ); 

    } 
); 

또는 다시 후 바로 $push 업데이트를 사용.

관련 문제