Is there anyway to enforce foreign key validation in mongodb?

As part of a research exercise, I am looking into if there is anyway we can enforce a foreign key validation in MongoDB. More specifically, when we insert a document in collection A that has references for documents in collection B, it checks to see if they are valid?

So far I do not see any way to do this inside MongoDB. Though I do see we can probably handle that through the application code. Just want to make sure this understanding is correct.

I actually just went through this very thing for a proof of concept project I’m working on, the short answer is no, you cannot enforce a foreign key validation without creating application logic for that specific use case/restriction.

You can use populate() to do this in mongoose, but I’m still trying to figure out a Driver way for this kind of logic, but overall MongoDB isn’t designed to do this organically. So do expect some performance impacts (minor) at the least from implementing this.

Also, this is more in line with schema-validation rather than key validation, so you can somewhat create references between documents that will only populate what has those references. But again, this isn’t exactly like foreign key validation.

as i recall, mongo manual doesn’t mention things like that. this is one difference from sql dbs.