How do I add an array of elements to a mongo document?

I am currently learning Meteor and doing so by writing an app that allows for creatings posts and then adding tags (like #meteor) to them.

I’m currently stuck on inserting a new document into my collection. My goal is to insert the content of the post and all tags that were included. The tags have been parsed out of the post content and added to a tags array.

Here is where I am calling the insert:

Template.newPost.events({
  "cick .save": function(event){
    var hashtagPattern = /#[A-Za-z0-9_]*/gi;
    var postContent = event.target.value;
    var tags = postContent.match(hashtagPattern);
    Meteor.call('newPost', postContent, tags);
    event.target.value = "";
 }); 

This is the Mongo Insert. The insert works fine without the “$push … tags” line.
The formatting of that line is based on : http://docs.mongodb.org/manual/reference/operator/update/each/
With it, I get errors such as “While building the application … Unexpected token {”

Meteor.methods({
  newPost: function(postContent,postContentTags){
    Posts.insert({
      content: postContent , 
      createdAt: new Date() , 
     { $push: { tags: {$each: postContentTags }}}
});

Since this clearly is incorrect, what is the correct way of inserting an array of elements (in this case tags) into a collection?

Any help or advice would be very much appreciated!

$push is modifier comand, you should use it with update not insert - insert waits plain js/json object, so you can pass your data as Posts.insert({content: postContent, createdAt: new Date(), tags: postContentTags});

1 Like

Thanks, that solved it!

Hello …
I know your Problem is solve
but learn More about $push

Insert single item into MongoDB Array using $push operator

/* Insert single number or string into MongoDB array - Construct input JSON as below */
{YourArrayField : 111 }

/* Insert single document into MongoDB array - Construct input JSON as below */
{YourArrayField : {OrderID:1, Total:20.00} }

For More about MongoDB update, delete and More Visit