programing

mongodb 업데이트에서 변수 사용

stoneblock 2023. 6. 28. 21:18

mongodb 업데이트에서 변수 사용

Meteor를 사용하여 다음과 같은 업데이트를 수행하려고 합니다.

Items.update(Session.get('selectedItem'), {'$set': {'directions.0.name': area.value}})

하지만 저는 방향의 배열 인덱스를 동적으로 설정하는 방법에 대해 고심하고 있습니다.

var index = //a value determined dynamically
Items.update(Session.get('selectedItem'), {'$set': {'directions[index]name': area.value}})

[index]가 문자열로 감싸져 있기 때문에 이 작업이 수행되지 않습니다.또한 다음과 같은 사용자 지정 문자열을 구성하려고 했습니다.

var string = 'directions.'+itemIndex+'.name'
Items.update(Session.get('selectedItem'), {'$set': {string: area.value}})

하지만 그것은 효과가 없습니다.어떻게 해야 할지 생각나는 거 있어요?

당신은 당신의 계획을 세울 필요가 있습니다.$set프로그래밍 방식으로 개체:

var setModifier = { $set: {} };
setModifier.$set['directions.' + index + '.name'] = area.value;
Items.update(Session.get('selectedItem'), setModifier);

갱신하다

JavaScript 환경에서 계산된 속성 이름(예: node.js 4+)을 지원하는 경우 다음 작업을 한 번에 수행할 수 있습니다.

Items.update(Session.get('selectedItem'), { $set: {
    ['directions.' + index + '.name']: area.value
}});

언급URL : https://stackoverflow.com/questions/12393351/using-a-variable-in-mongodb-update