Automattic / Automattic/mongoose
Foreign key like validation for mongoose referrence
- Dominant language
- JavaScript
- Stars
- 27.5k
- Forks
- 4k
- Avg merge
- 2d 7h
- Merged PRs (30d)
- 35
Description
**Do you want to request a *feature* or report a *bug*?**
I want to request a feature
**What is the current behavior?**
While mongoose `ref` property is a very powerful feature in itself as a replacement for joins with population, the fact that the ObjectId in that field may or may not correspond to an actual document in the referrenced collection paves way for bugs to creep in
Consider these models
```js
const companySchema = new mongoose.Schema({
name: String
});
let modelCompany = mongoose.model('company', companySchema);
const employeeSchema = new mongoose.Schema({
name: String,
companyId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'company'
},
});
let modelEmployee = mongoose.model('employee', employeeSchema);
```
Here I absolutely want for an employee to have a valid companyId in the sense that a company with that id must exist. Otherwise it shouldn't be stored in the database(the way foreign keys work in a relational database)
Currently we have to use a custom validator for it to ensure such such referrences are valid. And this is such a basic and essential feature, that a validator is one of the first thing I write whenever I start a new project with mongoDB + mongoose.
It would be really great if we can have this validation built in to the mongoose. We can have a property like `validateReferrences` that can be set to `true/false` for anyone to disable it if they don't want such a validation. And by setting it's default value to `false`, we can also make sure that it is backwards compatible
**What are the versions of Node.js, Mongoose and MongoDB you are using? Note that "latest" is not a version.**
Node.js: 12.10.0
MongoDb: 4.0.4
Mongoose: 5.6.11
Contributor guide
Research direction
Start by reviewing Mongoose's existing custom validation and ref/population behavior, using the employee and company models in the issue as the motivating case. Define the expected behavior for an optional built-in reference check, including its default and disabled states, then establish tests showing that invalid companyId references are rejected without breaking existing behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, mongodb, nodejs
- Domain
- backend, database
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100