Reputation: 1273
Trying to figure out how to pull off this query in MongoDB:
CategorySchema
const CategorySchema = new Schema({
// Declare a unique name for each category.
name: {
required: true,
type: String,
unique: true
},
// This is the object that contains the 3 responsive image collections.
photos: {
mobile: [],
tablet: [],
desktop: []
}
});
addPhoto()
/**
* addPhoto(arg, arg2, arg3)
* - @param {String} name
* - @param {Object} image
* - @param {String} type
* - @return {Promise}
* - NOTE: Schema.statics allows for creating methods
* - on the Schema class.
*/
CategorySchema.statics.addPhoto = async function (name, image, type) {
// Find category 'name' & push the imageUrl to the key 'photos' array.
const list = await this.findOneAndUpdate({ name }, { $push: { photos: image.url } });
// Return the updated category.
return list;
};
Initially addPhoto()
worked fine before changing photos
to an object containing the 3 arrays. Now I have addPhoto
accepting a third argument type
which will be one of the 3 keys in the photos
object.
Problem I'm running into is how to pull of this query. I query the collection by name because that is unique to each collection. photos
is present in each collection so I can't query that; but ultimately need to be able to access photos[type]
to perform the $push
. Any ideas on how I might be able to achieve that? I've been playing with a few different query operators but to no avail.
Upvotes: 0
Views: 34
Reputation: 1570
You need to update addPhoto function like
/**
* addPhoto(arg, arg2, arg3)
* - @param {Object} filter Eg {name: someName, type: someType}
* - @param {Object} image
* - @return {Promise}
* - NOTE: Schema.statics allows for creating methods
* - on the Schema class.
*/
CategorySchema.statics.addPhoto = async function (filter, image) {
// Find category 'name' & push the imageUrl to the key 'photos' array.
const list = await this.findOneAndUpdate(filter, { $push: { photos: image.url } });
// Return the updated category.
return list;
};
from this you can add more filter in future
Upvotes: 1