× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

$addToSet inserts empty object when used with meteor.js package simple-schema

Foysal
Jun 03, 2016
<p>This is a little bit counter-intuitive and made me lose a couple of hours but I guess this could be avoided by reading the docs properly. So I thought, I'd write up about it for the lazy googlers out there. <br> <br> If you're using simple-schema package and have a field that is supossed to be an array of objects like below </p> <p> </p> <pre><code class="language-javascript">new SimpleSchema({ "contacts": { type: [Object] } });</code></pre> <p>and you expect the contacts array to hold objects of the following structure: </p> <pre><code class="language-json">{ "name": "Foysal", "title": "science man" }</code></pre> <p>and then you try to insert new objects into the array using $addToSet operator, <strong>this will fail </strong>but not 100%. It will end up inserting an empty object. It's so simple that you've probably already figured out why but me being careless and not having my afternoon tea and all, took me a solid couple of hours to see why it wasn't working. VALIDATION. simple schema validates the object according to the schema definition and since we didn't define what data is allowed in the nested objects, it cleans up everything inside and inserts the empty object. <br> <br> To overcome this - you'll have to define the allowed keys in the schema definition as below:</p> <pre><code>new SimpleSchema({ "contacts": { type: [Object] }, "contacts.$.name": { type: String }, "contacts.$.title": { type: String } });</code></pre> <p>It will tell simple-schema what data to allow into the nested objects and allow you to ride your ride your unicorn into the rainbow land of meteor.js back again.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus