복붙노트

[MONGODB] MongoDB의 업데이트에 변수를 사용하여

MONGODB

MongoDB의 업데이트에 변수를 사용하여

유성 사용하여, 나는 다음과 같은 업데이트를 수행하기 위해 노력하고있어 :

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}})

[인덱스] 문자열에 싸여 있기 때문에 작동하지 않습니다. 또한 다음과 같이 사용자 정의 문자열을 형성하기 위해 노력했다 :

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

그러나 그것은 작동하지 않습니다. 이 작업을 수행하는 방법에 대한 어떤 생각?

해결법

  1. ==============================

    1.당신은 프로그래밍 방식 $ 세트 객체를 구축해야합니다 :

    당신은 프로그래밍 방식 $ 세트 객체를 구축해야합니다 :

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

    최신 정보

    자바 스크립트 환경에서 지원하는 (예를 들어, Node.js를 4+) 속성 이름을 계산하면 한 단계에서이 작업을 수행 할 수 있습니다 :

    Items.update(Session.get('selectedItem'), { $set: {
        ['directions.' + index + '.name']: area.value
    }});
    
  2. from https://stackoverflow.com/questions/12393351/using-a-variable-in-mongodb-update by cc-by-sa and MIT license