Yeats
Yeats

Reputation: 2065

Pushing object into array using MongoDB syntax and SimpleSchema validation

The idea is to push an object that looks like this into a field called likes, which is an array:

{
  movieId: "VgtyvjVUAjf8ya",
  information: {
                 genre: "Action",
                 length: "160",
                 language: "English"
               }
}

I thought this would do it:

Meteor.users.update({_id: Meteor.userId()}, {$push: {likes: {movieId: movieId, information: informationObj}}})

But either it is wrong or the validation by SimpleSchema has some issues (it doesn't complain, though) because all I get is an empty object in an array! And no, there's nothing wrong with the values themselves, I have checked.

The SimpleSchema for the field in question looks like this:

likes: {
            type: [Object],
            optional: true
        }

I've tried reading through the documentation but I don't really understand what's wrong. Anyone knows?

Upvotes: 3

Views: 671

Answers (1)

Sean
Sean

Reputation: 4515

If you don't care to validate the objects that get pushed into the likes property, you can set blackbox to true in your schema, like so:

likes: {
    type: [Object],
    optional: true,
    blackbox: true
}

This will allow you to put whatever you want into a "like" object.

If you do want to validate the "like" objects, then you'll need to create some additional schemas, like so:

var likeInfoSchema = new SimpleSchema({
    genre: {
        type: String
    },
    length: {
        type: String
    },
    language: {
        type: String
    }
});

var likeSchema = new SimpleSchema({
    movieId: {
        type: String
    },
    information: {
        type: likeInfoSchema
    }
});

Meteor.users.attachSchema(new SimpleSchema({
    // ...
    likes: {
        type: [likeSchema]
    }
}));

Upvotes: 7

Related Questions