In MongoDB, data is related across collections using something called references

In our TODO application, each todo refers to an entry in the users table.

Screenshot 2024-09-14 at 6.47.59 PM.png

Our original schema

const Todo = new Schema({
    userId: ObjectId,
    title: String,
    done: Boolean
});

Update schema with references

const TodoSchema = new Schema({
  userId: { type: Schema.Types.ObjectId, ref: 'users' },
  title: String,
  done: Boolean
});

Benefits?

You can pre-populate fields like user information since you’ve defined the exact relationship


app.get("/todos", auth, async function(req, res) {
    const userId = req.userId;

    const todos = await TodoModel.find({
        userId
    }).populate('userId').exec();

    res.json({
        todos
    })
});