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?


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.

  • Gotcha, I ended up implementing cloud code for this hook. definitely voted for next round of features, fingers crossed! – Steven_ Aug 16 '17 at 11:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.