How to update a form with multiple values ​​in ejs + mongoose?

The user has fields in mongoose that will be updated if the user decides to update.

Here is the user schema

var User = Schema({

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

Thus, the user has fields that they can update or add, for example, the user can add additional information about education and skills using the form.

How to do it correctly in ejs and route?

my attempt at 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();
    });

});

The value continues to push, I want, I know that it’s obvious that I click the data in the field, but how can I update it correctly?

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>

Is it true that I need for each cycle? if i want to update specific data?

+4
source share
2

1- :

, , - .

:

- , , ?

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

:

  • , . , - .
  • , , , , .
+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 . add "". , 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];
  }
};

Mongoose . , .

+2

Source: https://habr.com/ru/post/1614429/


All Articles