Express/Node.js — How to save an array of objects within one Model

Problem

Possible Duplicate:
 Mongoose — Form to save model with embedded documents

I have a simple Mongoose schema with BlogPosts and Feeds embedded within those BlogPosts. So each BlogPost can have several Feed objects. Right now my HTML form allows me to correctly save one ‘Feed’ when I create a BlogPost, BUT I would like to be able to add many Feeds. How should I change my HTML/controller? Thanks much!

web.js

app.post('/blogpost/new', function(req, res){
var post = new BlogPost(req.body.post)
post.feeds.push(req.body.feed);
post.save(function() {
res.redirect('/blogposts');
});
});

/blogpost/new

<form method="post">
<input type="text" name="blogpost[title]"/>
<textarea name="feed[name]"></textarea>
<textarea name="feed[key]"></textarea>
<textarea name="feed[name]"></textarea>
<textarea name="feed[key]"></textarea>
</form>

schema

var Feed = new Schema({
name : { type: String }
, key : { type: String }
});

var BlogPost = new Schema({
title : { type: String, required: true, index: { unique: true } }
, feeds : [Feed]
});

How do I make it so that this form stores two ‘Feeds’ in the blogpost object it creates? right now it would save One Feed in the data with two name values and two key values.

Thanks much!

Problem courtesy of: tuddy

Solution

When you do something like this:

<textarea name="feed[name]"></textarea>
<textarea name="feed[key]"></textarea>
<textarea name="feed[name]"></textarea>
<textarea name="feed[key]"></textarea>

You are basically saying “I need a textbox for feed’s name, feed’s key, feed’s name, feed’s key which is obviously incorrect. If you did feed[0][name]...feed[1][name] that would say "i need a textbox for the first feed...i need a textbox for the second feed"

Since you are breaking the parent and child up, rather than handling them as sub objects, you’ll need to push each into the blogPost.feeds and save it.

Just be careful with that approach, especially when editing, because you are simply adding new objects ontop of what could already be an existing array of feeds.

Solution courtesy of: Chance

View additional discussion.