Adding array into collection


I have two collections: Posts and Labels

My posts have a labels field where I want to insert an array with label ids (which the user picks from the Labels collection)

When I try to insert the labels in the Posts like this, it’s not working.

    title: title,
    description: description,
    labels: arrayWithSelectedLabels

How can I insert the array with label ids into the labels field of the Post?

That syntax looks OK.

We need to see what arrayWithSelectedLabels actually looks like (maybe do a

console.log(JSON.stringify(arrayWithSelectedLabels, null, 2));

just before your Posts.insert).

1 Like
  1. you did not provide error. “It does not work” is not the correct way how to define it.

  2. If you want “insert” into already existing document, it is called “update” and you want to $set that property to something.

So updating Posts document which have given _id and set it’s labels to some value (possibly array) could be done by:

Posts.update( {
    _id: postId
    $set:  {
      labels: arrayWithSelectedLabels
1 Like

Thank you for your answer.

Here’s what I get in the console.log

Meantime I also added simpleSchema and I noticed there is no Array as a Type. I can send strings, booleans, numbers and object. I guess I have to turn that array with label ids into an object? How would I do that?

Thank you for answering.

Well, the thing is I am not getting an error. My array is simply not written into the labels field of the post.
In this case I am not trying to do an update, I am trying to create a new post.

Here’s a part of my addPost template:

<input type="text" name="title" class="form-control">
<textarea name="description" id="description" class="form-control"></textarea>

{{#each labels}}
    <li class="list-group-item">
        <input type="checkbox" name="label" value="{{_id}}" class="label-checkbox">
        <label for="label" class="label-name">{{name}}</label>

So I have a form to fill data for the Post and I’m iterating over all the labels.
Then, in the addPost.Events I get all the values from the inputs, check which labels are checked by the user and send that info in the Posts collection.

There is array in SImple schema,
array of strings is [String], numbers [Number], objects [Object]

1 Like

Well… this was the big issue. I already used the brackets in the helper so I did not think I need to use them in the schema…

Thank you for your help!