Sunday, 2 April 2017

Mongoose - atomically update child schema

I have a schema and a child schema and I wonder what would be the best optimal way to update it.

//child schema
var menuIconsSchema = new mongoose.Schema({

    menuEntry: {
        type: String, 
        required: true, 
        unique: true,
    validate: { ... }
},

image: {
        type: String, 
        required: true,
        validate: { ... }

    }
})

var Site = new mongoose.Schema({
  //_id - unique user_id
id: { type: Number, required: true}, //this id is not unique globally, its unique to the user

userUID: { type: String, required: true } ,

settings: {
   colorScheme: { type: String, default: 'blue', enum: ['blue', 'indigo', 'green', 'pink', 'teal', 'lightGreen'] },

    //... more properties
},

menuIcons: { type: [menuIconsSchema], validate: [v => v.length <= 50, 'icon limit reached'] },

});

So far I've gotten to the point where I can update everything without getting any info prior from the db, like:

Site.update({ id: siteID, userUID: uid }, { $set: {

  'settings.colorScheme': 'green',
  'menuIcons.0': { menuEntry: 'test', image: 'test.svg' }

 } }, { runValidators: true }, function(err) { ... };

The problem is with the child schema menuIcons, I don't know which index to set. menuEntry is unique, if duplicate it should be replaced at the index that matches it, otherwise it would have to be pushed to the array. What would be the best way to do it? I guess I would have to get the whole schema from database first to determine which indexes should be updated. Is there a better way?

Note that I have to allow for adding/updating an unspecified number of documents to the child schema.



via Maciej Krawczyk

No comments:

Post a Comment