Jason Chen Jason Chen - 2 months ago 12
Javascript Question

NodeJS backend POST for array item?

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.

Answer

try

 user.person.push({"name":req.body.name}); 
Comments