#Mongodb doesnot validate reference in Schema

6 messages · Page 1 of 1 (latest)

somber oar
#

When creating a mongodb document with mongoose,

 @Prop({
    type: mongoose.Schema.Types.ObjectId,
    ref: 'USER',
    required: true,
  })
  user_id: User;

we can send a object id that user doesnot exits, mongoose doesnot validate that. Is there a inbuilt validation method, or any workaround

#

It creates a user record, without user existance

rich cipher
#

You are responsible for referential integrity. If you know there could be bad input given, then you need to validate it yourself. There is no quick fix and certainly no workaround. It's part of working with MongoDB. There are several ways to do it, but it depends on how your application works. For instance, if the data for the reference is coming from the client, you'd have maybe a pipe validating it. If the data for the reference is being generated server-side, but via code not in your control, you could create a method in your service or model. Or, you could use a Mongoose hook. All up to you.

#

There is also a number of plugins, like this one: https://www.npmjs.com/package/mongoose-references-integrity-checker

#

Sorry, that one is for integrity when deleting. This one is for checking the reference: https://www.npmjs.com/package/mongoose-reference-validator

#

It is a bit old though. You might have issues with it. Most of the time, these plugins are just hooks anyway. So, you could simply look into the code to get an idea of what they are doing and either do it yourself or fix the code, if there is a compatibility issue.