0

Sample JSON data, to show you how my MongoDB is arranged:

{
"state" : "California"
"person" [{"name": "Bob"}, {"name": "Bill"}]
}

I have an input form with the following POST value name and state in my HTML:

<input type="text" name="state" />
<input type="text" name="name"/>

Now, in order to process this POST, I have my Node route code arranged like so:

router.post('/profile', function(req, res, next) {
  User.findOne({ _id: req.user._id }, function(err, user) {

    if (err) return next(err);
    /*first action*/ 
    user.state = req.body.state;
    /*second action*/
    user.person.name = req.body.name; 

    user.save(function(err) {
      if (err) return next(err);
      req.flash('success', 'Purchase successful');
      return res.redirect('/profile');
    });
  });
});

Here is what's meant to happen. First, upon input and submission of state, the state (as shown in my DB) will change to whatever the user has typed. This works as intended.

Second, upon input and submission of name, there should be a new name added to the array.

The second action does not work. I have tried replacing the code with a push and for loop, like so:

for (var i = 0; i < user.person.length; i++){
user.push({
    name: person[i].name
});
}

This has not worked. I would also like to add that this is all meant to be rendered via ejs.

2 Answers 2

1

try

 user.person.push({"name":req.body.name}); 
Sign up to request clarification or add additional context in comments.

Comments

0

The thing is, user.person is an array - so you cannot access name like user.person.name -if you want to add a new name, then you need to access the person array and then push the new req.body.name - is this what you intend to do? In that case - this is what you should do:

//the rest of your code...
if (err) return next(err);
    /*first action*/ 
    user.state = req.body.state;
    /*second action*/
    //Here you PUSH the new name into this array
    user.person.push({'name':req.body.name}); 

    user.save(function(err) {
      if (err) return next(err);
      req.flash('success', 'Purchase successful');
      return res.redirect('/profile');
    });
//---the rest of your code

Give it a try and let me know if this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.