# 一对一
# 嵌套文档
{
"_id": "user1",
"name": "John Doe",
"profile": {
"id": "profile1",
"brief": "This is John's profile"
}
}
# 引用文档
// User 文档
{
"_id": "user1",
"name": "John Doe",
"profileId": "profile1"
}
// Profile 文档
{
"_id": "profile1",
"brief": "This is John's profile"
}
const user = await UserModel.findById('user1').populate('profileId').exec()
# 一对多
# 嵌套文档
{
"_id": "user1",
"name": "John Doe",
"posts": [
{ "id": "post1", "title": "Post 1" },
{ "id": "post2", "title": "Post 2" }
]
}
# 引用文档
// User 文档
{
"_id": "user1",
"name": "John Doe"
}
// Post 文档
{
"_id": "post1",
"title": "Post 1",
"userId": "user1"
}
{
"_id": "post2",
"title": "Post 2",
"userId": "user1"
}
const user = await UserModel.findById('user1').populate('profileId').exec()