Meteor-Community-Packages / meteor-collection2

A Meteor package that extends Mongo.Collection to provide support for specifying a schema and then validating against that schema when inserting and updating.
https://packosphere.com/aldeed/collection2
MIT License
1.02k stars 108 forks source link

Is it possible to create field type that takes key and value pair? #416

Closed Ziyad33 closed 4 years ago

Ziyad33 commented 4 years ago

I want to create an array type for comments that takes key and value pairs, user IDs as the key and their comment as the value,

I have tried the following:

comments: {
        type: [String, String],
        label: 'CommentsLabel',
        optional: true,
    },

But I realized that it doesn't seem to be the correct approach of defining an array with key and value pairs because when I try to insert one string into the comments array, it get inserted successfully,

I am looking for something similar to the dictionary in c#,

How should I go about creating a field that takes two pairs?

harryadel commented 4 years ago

I don't know about c# dictionary but you may try this:

comments: { type: Array },
'comments.$': { type: Object },
'comments.$.userId': { type: String },
'comments.$.comment': { type: String }

https://github.com/aldeed/simpl-schema#schema-keys

Ziyad33 commented 4 years ago

@harryadel thank you for the response,

I am a little confused on the code you posted and the related code on the package,

Is the following code correct if I wanted to add values to the userId and comment:?

Drawings.update({_id: id}, {$push: {'comments.$.userId':Meteor.userId(), 'comments.$.comment': 
document.getElementById('commentTextArea').value}}, function(error) {
                    if(error) {
                        console.log('Error : ' + error)
                    } else {
                        console.log('BINGO!!')
                    }
                });

and will every comment be linked to the userId?

I am sorry for my newb question and I hope it is clear :)

harryadel commented 4 years ago

You don't have to supply the sub fields but rather provide the new element as a whole to be pushed into the array like so:


Collection.update(
  { _id: '1' },
  {
    $push: {
      comments: {
        userId: 'xxx',
        comment: 'hello',
      },
    },
  },
);
Ziyad33 commented 4 years ago

@harryadel I really appreciate your help, you just helped me achieve what I wanted, thanks A LOT