简体   繁体   中英

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?

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]
    }
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM