The length of the meteoric length of the massif in Mongodba
In my user profile collection, I have an array with image objects.
A user can have a maximum of 3 images in their profile collection. If user has 3, make a mistake to max out. The user has the ability to independently delete the image in the external interface.
I thought the solution would be to check the length of the $ sized array. if it is less than 3, insert the image, otherwise fail.
I am using tomi: upload-jquery package.
customer:
Template.uploadImage.helpers({
uploadUserData: function() {
return Meteor.user();
},
finishUpload: function() {
return {
finished: function(index, fileInfo, context) {
Meteor.call('insert.profileImage', fileInfo, function(error, userId) {
if (error) {
// todo: display modal with error
return console.log(error.reason);
} else {
// console.log('success ' +userId);
// console.log('success ' + fileInfo);
}
});
}
};
}
});
Method used (server):
'insert.profileImage': function(postImage) {
check(postImage, Object);
// check array profile.images max 3
Meteor.users.update(this.userId, {
$push: {
'profile.images': postImage
}
});
},
source to share
You can do it with the function $where
:
'insert.profileImage': function(postImage) {
var updateResults;
check(postImage, Object);
updateResults = Meteor.users.update(
{
_id : this.userId,
$where : 'this.profile.images.length < 3' //'this' is the tested doc
},
{
$push: {
'profile.images': postImage
}
});
if(updateResults === 0) {
throw new Meteor.Error('too-many-profile-images',
'A user can only have up to 3 images on his/her profile');
}
},
Mongo docs warns of potential performance issues (if you run a JavaScript function on all docs in the store, you're in a bad state of surprises), but since we're also searching by _id
, I think it should be fine.
Thus, the update simply fails if the user has too many images. You can also check the number of damaged documents ( return valueupdate
) to see if something happened. If nothing (return 0
) happened, it has few options: the user has too many images.
source to share
Use the operator to check for the presence of all documents that have at least the fourth image profile array (index position 3) with the designation . For example, you can use it to check if the size of an array is more than 3 using the following: $exists
profile.image
find()
var hasSizeGreaterThanThree = Meteor.users.find(
{
'_id': this.userId,
'profile.image.3': { '$exists': true }
}).count() > 0;
Thus, you can use this in your code like:
'insert.profileImage': function(postImage) {
check(postImage, Object);
// check array profile.images max 3
var hasSizeGreaterThanThree = Meteor.users.find(
{
'_id': this.userId,
'profile.image.3': { '$exists': true }
}).count() > 0;
if (!hasSizeGreaterThanThree){
Meteor.users.update(this.userId, {
$push: {
'profile.images': postImage
}
});
}
},
source to share