Jason Chen Jason Chen - 1 year ago 77
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
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
, 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
, there should be a new
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++){
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 Source


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download