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.
const Todo = new Schema({
userId: ObjectId,
title: String,
done: Boolean
});
const TodoSchema = new Schema({
userId: { type: Schema.Types.ObjectId, ref: 'users' },
title: String,
done: Boolean
});
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
})
});