Jack Moscovi
Jack Moscovi

Reputation: 2269

How do i save a sub document's array in mongoose?

I've seen a lot of examples, how to update an array, like this one Mongoose find/update subdocument and this one Partial update of a subdocument with nodejs/mongoose

but my objective is to update a specific field, for example in a Form, where user enters data.

I'm using ejs for templating.

Here's the code

For clarity , here is User's Schema

var UserSchema = mongoose.Schema({
   resume: {
     education: [{ type: String}],
   }

});

Routing code

router.post('/update-resume', function(req, res) {
    User.findById(req.user._id, function(err, foundUser) {

        // Take a look over here, how do I update an item in this array?
        if (req.body.education) foundUser.resume.education.push(req.body.education);

        foundUser.save(function(err) {
            if (err) return next(err);
            req.flash('message', 'Successfully update a resume');
            return res.redirect('/update-resume')
        });
    });

});

If you take a look at the code above, my objective is to query a user data which is resume, and update its current value.

Code for the front end

<form role="form" method="post">
  <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>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Frontend code does work, it iterate in each user.resume.education array, and show all the values in the array. But how do I update it?

Upvotes: 0

Views: 3344

Answers (1)

udidu
udidu

Reputation: 8588

Since you're using .push() to the education array, mongoose don't know that this field has changed, you need to specify it with the markModified() function so mongoose will know that this field has changed, so, after you push to the education array use:

foundUser.markModified('resume.education');

and then use the save() function

UPDATE:

router.post('/update-resume', function(req, res) {
    User.findById(req.user._id, function(err, foundUser) {

        // Take a look over here, how do I update an item in this array?
        if (req.body.education) foundUser.resume.education.push(req.body.education);

        foundUser.markModified('resume.education'); // <-- ADDITION

        foundUser.save(function(err) {
            if (err) return next(err);
            req.flash('message', 'Successfully update a resume');
            return res.redirect('/update-resume')
        });
    });

});

Upvotes: 3

Related Questions