2016-06-20 6 views
0

중첩 된 var를 업데이트 할 때 명시/몽구스 코드에서 업데이트하지 않은 객체의 다른 중첩 된 vars를 삭제합니까?mongoose findOneAndUpdate는 중첩 된 vars를 삭제합니다.

내 스키마 :

var MySchema = new Schema({ 
    active: { type: Boolean, required: true, default: true }, 
    myvar: { 
    useDefault: { type: Boolean, required: true }, 
    custom: { type: String }, 
    default: { type: String } 
    } 
}); 

내 특급 미들웨어 업데이트 기능 :

var updateData = req.body; 
MySchema.findOneAndUpdate({ active: true }, updateData, function(err, myschema) { 
    if (err) throw err; 
    if (!myschema) { response(403, { success:false, message: "myschema not updated." }, res); } 
    // success 
    response(200, { success:true, message: "myschema updated." }, res); 
}); 

기록은 처음과 같이 :

{ 
    "myvar": { 
     "useDefault": true, 
     "custom": "some custom var", 
     "default": "some value" 
    } 
} 

나는 myVar에 말을 업데이트를 제출하는 경우 .useDefault 값은 다음과 같이 끝납니다.

{ 
    "myvar": { 
     "useDefault": false 
    } 
} 

대상 var 만 업데이트하고 다른 vars는 그대로 두는 방법에 대해 조언 해 줄 수 있습니까?

+2

헤이 왜 사용하지 않는 : 내 프로젝트에 대한 ES5) 기능을 toDot을 (변환했다, 여기에 원래 ES6 버전입니다 {myvar.userdefault : req.body.myvar.userdefault}}, function (err, myschema) { –

+0

어떤 속성이 업데이트되는지 알지 못하기 때문에 3 개 필드 모두 2 개 또는 하나 일 수 있습니다. – msmfsd

답변

0

응답은 response.body 객체를 점 표기법으로 변환하고 수정 된 객체를 몽고인 findOneAndUpdate로 전달하는 것이 었습니다. 답과 그의 toDot 기능에 대한 Gitter의 @btkostner에게 감사드립니다.

function(req, res) { 
    // convert response to dot notation so objects retain other values 
    var dotData = toDot(req.body, '.'); 
    MySchema.findOneAndUpdate({ active: true }, dotData, function(err, myschema) { 
    ... 
} 

// author: @btcostner 
function toDot (obj, div, pre) { 
    if (typeof obj !== 'object') { 
    throw new Error('toDot requires a valid object'); 
    } 
    if (pre != null) { 
    pre = pre + div; 
    } else { 
    pre = ''; 
    } 
    var iteration = {}; 
    Object.keys(obj).forEach(function(key) { 
    if (_.isPlainObject(obj[key])) { 
     Object.assign(iteration, _this.toDot(obj[key], div, pre + key)); 
    } else { 
     iteration[pre + key] = obj[key]; 
    } 
    }); 
    return iteration; 
}; 

참고 : 여기에 코드의 관련 비트 github.com/elementary/houston/blob/master/src/lib/helpers/dotNotation.js

관련 문제