2015-11-04 50 views
4

用戶擁有貓鼬中的字段,如果用戶決定更新,它將得到更新。如何更新在ejs + mongoose中有多個值的表單?

這裏的用戶模式

var User = Schema({ 

    education: [{ type: String}], 
}); 

所以基本上一個用戶,他們可以更新或添加,例如用戶可以添加額外的教育和使用形式的技能信息字段。

如何在ejs和路線中正確做到這一點?

我試圖在route.js

router.post('/update-resume', function(req, res) { 
    User.findById(req.user._id, function(err, foundUser) { 
     // This part how do I update ? 
     if (req.body.education) foundUser.resume.education.push(req.body.education); 

     foundUser.save(); 
    }); 

}); 

價值不斷推進,我想,我知道這是很明顯,我推數據到外地,但我怎麼更新正常嗎?

Form.ejs

<div class="form-group"> 
    <label for="education">Education:</label> 
    <% for(var i = 0; i < user.resume.education.length; i++) { %> 
    <input type="text" class="form-control" name="education" id="education" value="<%= user.resume.education[i] %>"> 
    <% } %> 
    </div> 

這是真的,我需要爲每個循環領域?如果我想更新具體數據?

回答

2

第一種選擇:

取決於你如何使用的應用程序,你可能甚至不關心更新 - 你可以只刪除以前的教育和保存新的來代替。

第二個選項:

正確地更新你真的需要某種形式的,你可以參考更新時的ID的,對不對?

您仍然需要使用您的for循環,您只需要插入id隱藏字段。

爲此,您需要傳遞一個對象而不是唯一的字符串值。我已經做了我的對象數組是這樣的:

var education = [ 
    {content:'Education 1',id:1}, 
    {content:'Education 2',id:3}, 
    {content:'Education 3',id:5}, 
    {content:'Education 4',id:2}, 
]; 

然後,你可以做這樣的事情:

<% for(var i = 0; i < education.length; i++) { %> 
<input type="hidden" type="hidden" name="education_id" value="<%= education[i].id %>"/> 
<input type="text" class="form-control" name="education" id="education" value="<%= education[i].content %>"> 
<% } %> 

陣列總是會得到通過你它發送到服務器的方式。就我而言,我會得到這個(你可以看到,一切都在秩序,它應該是):

{education_id: [ '1', '3', '5', '2' ], 
    education: [ 'Education 1', 'Education 2', 'Education 3', 'Education 4' ] } 

現在,讓我們來看看POST後端,則需要配合一切回到一個對象(你並不真的需要,但你可以,也許應該理智的緣故):

var education_i; 
var education_req = []; 
for(education_i=0;education_i<req.body.education.length;education_i++) { 
    console.log(req.body.education[education_i]); 
    education_req.push({ 
     content:req.body.education[education_i], 
     id:req.body.education_id[education_i] 
    }); 
} 

一些更多的注意事項:

  • 你必須檢查每一個教育用戶記錄。你不想讓任何人混淆ID並毀掉別人的個人資料。
  • 您應該單獨在循環外部保存數組長度變量,因爲它可能會導致超大型數組上的性能問題,因爲在每次循環迭代時會分析長度。
2

這是正路我會做到這一點:

型號:

var User = new Schema({ 
    education: [{ content: String }] 
}); 

的EJS/HTML:

<form id="education"> 
    <% user.education.forEach(function(item) { %> 
    <input type="text" data-id="<%= item.id %>" value="<%= item.content %>" /> 
    <% }); %> 
    <button type="submit">Save</button> 
</form> 

客戶端的JavaScript(JQuery的):

$('#education').on('submit', function(e) { 
    e.preventDefault(); 

    var data = []; 
    $(this) 
    .find('input') 
    .each(function() { 
     var $this = $(this); 

     // Collect the data with the id and value 
     data.push({ 
     id: $this.data('id'), 
     value: $this.val() 
     }); 
    }); 


    $.ajax({ 
    url: '/update-resume', 
    type: 'post', 
    data: { data: JSON.stringify(data) } 
    }) 
    .done(function(data) { 
     if (data.success) { 
     // Lazy: refresh window 
     window.location.reload(); 
     } 
    }) 
    .fail(function() { 
     // Show an error or something fancy 
    }); 
}); 

上述JavaScript將從輸入和值中讀取數據ID並將其放入教育對象數組中。然後它會將對象添加和字符串串化爲關鍵字'data'。這意味着你可以從req.body.data的路線中拉出字符串並解析它。

服務器端JavaScript /的路線:

router.post('/update-resume', function(req, res, next) { 
    User.findById(req.user._id, function(err, user) { 
    var parsed = JSON.parse(req.body.data); 


    // update and remove 
    var results = user 
     .education 
     .filter(function(item) { 
     return parsed.some(function(input) { 
      return input.id === item.id; 
     }); 
     }) 
     .map(function(item) { 
     var related = getRelated(item.id, parsed); 
     return { content: related.value }; 
     }); 

    // Add new items 
    user.education = results 
     .concat(parsed.reduce(function(prev, curr) { 
     if (!getRelated(curr.id, results)) { 
      prev.push({ content: curr.value }); 
     } 
     return prev; 
     }, [])); 

    user.save(function(err) { 
     if (err) return next(err); 
     res.json({ success: true }); 
    }); 
    }); 
}); 

獲得相關幫助:

var getRelated = function(id, arr) { 
    for (var i = 0; i < arr.length; i++) { 
    if (String(arr[i].id) === String(id)) return arr[i]; 
    } 
}; 

貓鼬會自動給你的教育數組項的ID。以上將允許您添加,刪除和更新頁面上的現有教育項目。

+0

我試過了,特別是在JSON.parse中出現了很多錯誤 - >不斷收到意外的令牌。你確定它是req.body.data?因爲html是data-id。 –

+0

傑克,我已經添加了客戶端JavaScript的簡要說明,以解釋它做了什麼。如果你在頁面下方的頁面上有它,它將完成所有艱苦的工作並對它創建的數組進行字符串化。應該沒有解析錯誤,因爲它只是一個字符串化的對象(由JSON完成,所以它應該是有效的)。你能粘貼錯誤嗎? – Rick

相關問題