2016-10-12 4 views
1

내 MongoDB를의 하위 문서는 같은 수 있습니다 :MongoDB의 하위 배열 요소의 수량 증가 업데이트

{ 
_id:"57beb7396366ebda090bf5ca" 
category:"Test" 
code:"L-001" 
created:"2016-08-25T09:15:37.184Z" 
description:"test" 
name:"Litu" 
price:2 
variant:[{ 
_id:"57beb7396366ebda090bf5ce" 
color:"Red" 
quantity:2 
size:"XL" 
},{ 
_id:"57beb7396366ebda090bf5fe" 
color:"Black" 
quantity:6 
size:"XXL" 
}] 

}

내가하는 색상 양을 줄이려 : 블랙 & 크기 : XXL

내가 가진

을 시도 :

Product.update({ 
     '_id' : req.body.id, 
     'variant.color' : req.body.color, 
     'variant.size' : req.body.size 
     }, 
     { 
      $inc: { 'variant.quantity' : -(req.body.quantity)} 
     }) 

오류가 발생했습니다. 오류 :

MongoError는 : 업데이트 배열 사용 번째 포지션/위치 연산자 ($) 내의 필드에 액세스하기 위해 소자

답변

3

을 통과하는 부분 (variant.quantity의 변형)을 사용할 수 없다.

이 경우 위치 연산자 $을 사용하십시오. 쿼리와 일치하는 배열의 첫 번째 요소를 업데이트합니다.

$inc: { 'variant.$.quantity' : -(req.body.quantity)} 
+2

감사합니다. 그것은 작동합니다 –

+1

@ Md.NazmulHossainBilash 우리는 [우리를 도운 응답을 받아 주셔서 감사합니다] (http://stackoverflow.com/help/accepted-answer). 왼쪽 옆에있는 체크 표시 옆에 녹색 체크 표시가 있습니다. :) – chridam