'The most efficient way to handle one to many relationship in MongoDB
Let's say I have a one-to-many relationship - A user has many todos. I want to be able to perform the following:
- Give me a specific user without the todos
- Give me the todos belongs to a specific user
- Give me a single todo by id
- Add, update, and delete todo
I can tackle it in three ways:
Embedding the todos inside the user document
import { Schema, model } from 'mongoose';
const userSchema = model('User', new Schema({
name: String,
todos: [{ title: String, id: String }],
}));
Use Todo Ref
import { Schema, model } from 'mongoose';
const userSchema = model('User', new Schema({
name: String,
todos: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Todo"
}],
}));
const todoSchema = model('Todo', new Schema({
name: String
}));
Use Todo Id
import { Schema, model, ObjectId } from 'mongoose';
const userSchema = model('User', new Schema({
name: String
}));
const todoSchema = model('Todo', new Schema({
name: String,
userId: ObjectId
}));
What will be the most efficient way to handle this scenario in MongoDB? Adding an index on the userId property in the last solution will make the query faster?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
