MongoDB 3.2 $ifNull with Validator – How to Use

mongodbnosql

I'm trying to achieve a document validator that checks if a user signs up with an avatar to their user profile. If they didn't attach an avatar I want to use something like $ifNull to set the default image:

db.runCommand({
collMod: "User",
validator: { $or: [
{ avatar: { $ifNull: [ "$avatar", "default-avatar.png"] } }
]},
validationLevel: "strict"
})

However, it seems like MongoDB separates document validation and it's aggregation methods… Is there a way to do this so that it will stay as a rule on a collection?

Best Answer

As you have noticed, right now this kind of "validation" is not possible in the mongodb. However, there is feature request open for such feature. If you give your 'vote' for it, maybe they make this feature. ;-)

Currently, the easiest way to archive that is do check (like that) in your application, just before inserting (or updating) document.