Trong hướng dẫn này, tôi sẽ chỉ cho bạn cách đối phó với MongoDB nhiều mối quan hệ, đây là mối quan hệ quan trọng và phức tạp mà bạn sẽ sử dụng trong hầu hết các cấu trúc cơ sở dữ liệu. Sau đó, chúng tôi sẽ sử dụng Thư viện Mongoose để làm một ví dụ về MongoDB cho nhiều mối quan hệ.
Bài viết liên quan:-Hướng dẫn mối quan hệ một-một với MongoDB với ví dụ Mongoose-Hướng dẫn mối quan hệ một-nhiều của MongoDB với các ví dụ Mongoose
– MongoDB One-to-One relationship tutorial with Mongoose example
–
MongoDB One-to-Many Relationship tutorial with Mongoose examples
- Node.js, Express & MongoDB: Xây dựng ví dụ API REST CRUD - Node.js + MongoDB: Xác thực và ủy quyền của người dùng với JWT
– Node.js + MongoDB: User Authentication & Authorization with JWT
Nội dung
- Mô hình các mối quan hệ nhiều-nhiều-nhiều trong MongoDB
- Các mô hình dữ liệu được nhúng [denqualization]
- Mô hình dữ liệu tham chiếu [bình thường hóa]
- Tài liệu tham khảo hoặc nhúng cho mối quan hệ nhiều-nhiều của MongoDB
- Ví dụ về mối quan hệ nhiều-đến nhiều của Mongoose
- Thiết lập ứng dụng Node.js
- Xác định mô hình dữ liệu Mongoose
- Sử dụng các chức năng mô hình Mongoose để tạo tài liệu
- Các tài liệu tham khảo
- Sự kết luận
- Mã nguồn
- Đọc thêm
Mô hình các mối quan hệ nhiều-nhiều-nhiều trong MongoDB
Các mô hình dữ liệu được nhúng [denqualization]
- Mô hình dữ liệu tham chiếu [bình thường hóa]
- Tài liệu tham khảo hoặc nhúng cho mối quan hệ nhiều-nhiều của MongoDB
Ví dụ về mối quan hệ nhiều-đến nhiều của Mongoose
Thiết lập ứng dụng Node.js
Các mô hình dữ liệu được nhúng [denqualization]
Mô hình dữ liệu tham chiếu [bình thường hóa]
Tài liệu tham khảo hoặc nhúng cho mối quan hệ nhiều-nhiều của MongoDB
// Tutorial
{
_id: "5db579f5faf1f8434098f123"
title: "Tut #1",
author: "bezkoder"
tags: [
{
name: "tagA",
slug: "tag-a"
},
{
name: "tagB",
slug: "tag-b"
}
]
}
// Tag
{
_id: "5db579f5faf1f84340abf456"
name: "tagA",
slug: "tag-a"
tutorials: [
{
title: "Tut #1",
author: "bezkoder"
},
{
title: "Tut #2",
author: "zkoder"
}
]
}
Mô hình dữ liệu tham chiếu [bình thường hóa]
Tài liệu tham khảo hoặc nhúng cho mối quan hệ nhiều-nhiều của MongoDB
Ví dụ về mối quan hệ nhiều-đến nhiều của Mongoose
Thiết lập ứng dụng Node.js
// Tags
// tagA: [Tut #1, Tut #2]
{
_id: "5db57a03faf1f8434098ab01",
name: "tagA",
slug: "tag-a",
tutorials: [ "5db579f5faf1f8434098f123", "5db579f5faf1f8434098f456" ]
}
// tagB: [Tut #1]
{
_id: "5db57a04faf1f8434098ab02",
name: "tagB",
slug: "tag-b",
tutorials: [ "5db579f5faf1f8434098f123" ]
}
Xác định mô hình dữ liệu Mongoose
This type of referencing is called Child Referencing: the parent [Tag] references its children [Tutorials].
Sử dụng các chức năng mô hình Mongoose để tạo tài liệu
Each child document keeps a reference to the parent element.
Các tài liệu tham khảo
// Tutorial
// Tut #1: [tagA, tagB]
{
_id: "5db579f5faf1f8434098f123"
title: "Tut #1",
author: "bezkoder"
tags: [ "5db57a03faf1f8434098ab01", "5db57a04faf1f8434098ab02" ],
}
// Tut #2: [tagA]
{
_id: "5db579f5faf1f8434098f456"
title: "Tut #2",
author: "zkoder"
tags: [ "5db57a03faf1f8434098ab01" ],
}
Sự kết luậnTwo-way Referencing where Tags and Tutorials are connected in both directions:
– In each Tag, we keep
references to all Tutorials that are tagged.
– In each Tutorial, we also keep references to its Tags.
Tài liệu tham khảo hoặc nhúng cho mối quan hệ nhiều-nhiều của MongoDB
Ví dụ về mối quan hệ nhiều-đến nhiều của Mongoose
Thiết lập ứng dụng Node.js
And the risk is so serious in case we want to update document, even just a field, we have to find and update two place.
Xác định mô hình dữ liệu Mongoose
Sử dụng các chức năng mô hình Mongoose để tạo tài liệualways use Data References or Normalizing the data.
Thiết lập ứng dụng Node.js
Xác định mô hình dữ liệu Mongoosemongoose with the command:
npm install mongoose
Sử dụng các chức năng mô hình Mongoose để tạo tài liệu
Các tài liệu tham khảo
Sự kết luận
Mã nguồn
Đọc thêm
Hãy suy nghĩ về một blog hướng dẫn với mối quan hệ giữa hướng dẫn và thẻ đi theo cả hai hướng:
Một hướng dẫn có thể có nhiều thẻ
Một thẻ có thể trỏ đến nhiều hướng dẫn
Chúng tôi gọi họ là nhiều mối quan hệ nhiều.
const mongoose = require["mongoose"];
mongoose
.connect["mongodb://localhost/bezkoder_db", {
useNewUrlParser: true,
useUnifiedTopology: true
}]
.then[[] => console.log["Successfully connect to MongoDB."]]
.catch[err => console.error["Connection error", err]];
Hãy cùng khám phá cách chúng trông như thế nào sau khi chúng tôi thực hiện hai cách mô hình hóa các bộ dữ liệu này.
module.exports = {
Tag: require["./Image"],
Tutorial: require["./Tutorial"]
};
Chúng ta có thể từ chối dữ liệu vào một hình thức được chuẩn hóa chỉ bằng cách nhúng các tài liệu liên quan ngay vào tài liệu chính.mongoose to interact with MongoDB database.
Xác định mô hình dữ liệu Mongoose
Sử dụng các chức năng mô hình Mongoose để tạo tài liệu
const mongoose = require["mongoose"];
const Tag = mongoose.model[
"Tag",
new mongoose.Schema[{
name: String,
slug: String,
tutorials: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Tutorial"
}
]
}]
];
module.exports = Tag;
Các tài liệu tham khảo
Sự kết luận
Mã nguồn
const mongoose = require["mongoose"];
const Tutorial = mongoose.model[
"Tutorial",
new mongoose.Schema[{
title: String,
author: String,
tags: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Tag"
}
]
}]
];
module.exports = Tutorial;
Sử dụng các chức năng mô hình Mongoose để tạo tài liệu
Các tài liệu tham khảo
4npm install mongoose
5npm install mongoose
6npm install mongoose
7npm install mongoose
Mở máy chủ.js, thêm mã bên dưới:
const mongoose = require["mongoose"];
const db = require["./models"];
const createTutorial = function[tutorial] {
return db.Tutorial.create[tutorial].then[docTutorial => {
console.log["\n>> Created Tutorial:\n", docTutorial];
return docTutorial;
}];
};
const createTag = function[tag] {
return db.Tag.create[tag].then[docTag => {
console.log["\n>> Created Tag:\n", docTag];
return docTag;
}];
};
const addTagToTutorial = function[tutorialId, tag] {
return db.Tutorial.findByIdAndUpdate[
tutorialId,
{ $push: { tags: tag._id } },
{ new: true, useFindAndModify: false }
];
};
const addTutorialToTag = function[tagId, tutorial] {
return db.Tag.findByIdAndUpdate[
tagId,
{ $push: { tutorials: tutorial._id } },
{ new: true, useFindAndModify: false }
];
};
const run = async function[] {
var tut1 = await createTutorial[{
title: "Tut #1",
author: "bezkoder"
}];
var tagA = await createTag[{
name: "tagA",
slug: "tag-a"
}];
var tagB = await createTag[{
name: "tagB",
slug: "tag-b"
}];
var tutorial = await addTagToTutorial[tut1._id, tagA];
console.log["\n>> tut1:\n", tutorial];
var tag = await addTutorialToTag[tagA._id, tut1];
console.log["\n>> tagA:\n", tag];
tutorial = await addTagToTutorial[tut1._id, tagB];
console.log["\n>> tut1:\n", tutorial];
tag = await addTutorialToTag[tagB._id, tut1];
console.log["\n>> tagB:\n", tag];
var tut2 = await createTutorial[{
title: "Tut #2",
author: "zkoder"
}];
tutorial = await addTagToTutorial[tut2._id, tagB];
console.log["\n>> tut2:\n", tutorial];
tag = await addTutorialToTag[tagB._id, tut2];
console.log["\n>> tagB:\n", tag];
};
mongoose
.connect["mongodb://localhost/bezkoder_db", {
useNewUrlParser: true,
useUnifiedTopology: true
}]
.then[[] => console.log["Successfully connect to MongoDB."]]
.catch[err => console.error["Connection error", err]];
run[];
Chạy ứng dụng với lệnh:
npm install mongoose
8. Bạn có thể thấy kết quả trong bảng điều khiển.You can see the result in Console.
Successfully connect to MongoDB.
>> Created Tutorial:
{ tags: [],
_id: 5e417363316cab53182888d8,
title: 'Tut #1',
author: 'bezkoder',
__v: 0 }
>> Created Tag:
{ tutorials: [],
_id: 5e417363316cab53182888d9,
name: 'tagA',
slug: 'tag-a',
__v: 0 }
>> Created Tag:
{ tutorials: [],
_id: 5e417363316cab53182888da,
name: 'tagB',
slug: 'tag-b',
__v: 0 }
>> tut1:
{ tags: [ 5e417363316cab53182888d9 ],
_id: 5e417363316cab53182888d8,
title: 'Tut #1',
author: 'bezkoder',
__v: 0 }
>> tagA:
{ tutorials: [ 5e417363316cab53182888d8 ],
_id: 5e417363316cab53182888d9,
name: 'tagA',
slug: 'tag-a',
__v: 0 }
>> tut1:
{ tags: [ 5e417363316cab53182888d9, 5e417363316cab53182888da ],
_id: 5e417363316cab53182888d8,
title: 'Tut #1',
author: 'bezkoder',
__v: 0 }
>> tagB:
{ tutorials: [ 5e417363316cab53182888d8 ],
_id: 5e417363316cab53182888da,
name: 'tagB',
slug: 'tag-b',
__v: 0 }
>> Created Tutorial:
{ tags: [],
_id: 5e417363316cab53182888db,
title: 'Tut #2',
author: 'zkoder',
__v: 0 }
>> tut2:
{ tags: [ 5e417363316cab53182888da ],
_id: 5e417363316cab53182888db,
title: 'Tut #2',
author: 'zkoder',
__v: 0 }
>> tagB:
{ tutorials: [ 5e417363316cab53182888d8, 5e417363316cab53182888db ],
_id: 5e417363316cab53182888da,
name: 'tagB',
slug: 'tag-b',
__v: 0 }
Các tài liệu tham khảo
Bạn có thể thấy rằng trường mảng ________ 21/________ 33 chứa ID tham chiếu. Đây là thời gian để sử dụng hàm
const mongoose = require["mongoose"];
mongoose
.connect["mongodb://localhost/bezkoder_db", {
useNewUrlParser: true,
useUnifiedTopology: true
}]
.then[[] => console.log["Successfully connect to MongoDB."]]
.catch[err => console.error["Connection error", err]];
1 để có được dữ liệu đầy đủ. Hãy để tạo ra hai chức năng:This is the time to use
const mongoose = require["mongoose"];
mongoose
.connect["mongodb://localhost/bezkoder_db", {
useNewUrlParser: true,
useUnifiedTopology: true
}]
.then[[] => console.log["Successfully connect to MongoDB."]]
.catch[err => console.error["Connection error", err]];
1 function to get full data. Let’s create two functions:
2const mongoose = require["mongoose"]; mongoose .connect["mongodb://localhost/bezkoder_db", { useNewUrlParser: true, useUnifiedTopology: true }] .then[[] => console.log["Successfully connect to MongoDB."]] .catch[err => console.error["Connection error", err]];
3const mongoose = require["mongoose"]; mongoose .connect["mongodb://localhost/bezkoder_db", { useNewUrlParser: true, useUnifiedTopology: true }] .then[[] => console.log["Successfully connect to MongoDB."]] .catch[err => console.error["Connection error", err]];
// Tags
// tagA: [Tut #1, Tut #2]
{
_id: "5db57a03faf1f8434098ab01",
name: "tagA",
slug: "tag-a",
tutorials: [ "5db579f5faf1f8434098f123", "5db579f5faf1f8434098f456" ]
}
// tagB: [Tut #1]
{
_id: "5db57a04faf1f8434098ab02",
name: "tagB",
slug: "tag-b",
tutorials: [ "5db579f5faf1f8434098f123" ]
}
0Chạy lại, kết quả sẽ trông như thế này-
// Tags
// tagA: [Tut #1, Tut #2]
{
_id: "5db57a03faf1f8434098ab01",
name: "tagA",
slug: "tag-a",
tutorials: [ "5db579f5faf1f8434098f123", "5db579f5faf1f8434098f456" ]
}
// tagB: [Tut #1]
{
_id: "5db57a04faf1f8434098ab02",
name: "tagB",
slug: "tag-b",
tutorials: [ "5db579f5faf1f8434098f123" ]
}
1Nếu bạn không muốn nhận
const mongoose = require["mongoose"];
mongoose
.connect["mongodb://localhost/bezkoder_db", {
useNewUrlParser: true,
useUnifiedTopology: true
}]
.then[[] => console.log["Successfully connect to MongoDB."]]
.catch[err => console.error["Connection error", err]];
4 & const mongoose = require["mongoose"];
mongoose
.connect["mongodb://localhost/bezkoder_db", {
useNewUrlParser: true,
useUnifiedTopology: true
}]
.then[[] => console.log["Successfully connect to MongoDB."]]
.catch[err => console.error["Connection error", err]];
5 trong kết quả mảng, chỉ cần thêm các tham số thứ hai vào hàm const mongoose = require["mongoose"];
mongoose
.connect["mongodb://localhost/bezkoder_db", {
useNewUrlParser: true,
useUnifiedTopology: true
}]
.then[[] => console.log["Successfully connect to MongoDB."]]
.catch[err => console.error["Connection error", err]];
1.// Tags
// tagA: [Tut #1, Tut #2]
{
_id: "5db57a03faf1f8434098ab01",
name: "tagA",
slug: "tag-a",
tutorials: [ "5db579f5faf1f8434098f123", "5db579f5faf1f8434098f456" ]
}
// tagB: [Tut #1]
{
_id: "5db57a04faf1f8434098ab02",
name: "tagB",
slug: "tag-b",
tutorials: [ "5db579f5faf1f8434098f123" ]
}
2Kết quả là khác nhau bây giờ.
// Tags
// tagA: [Tut #1, Tut #2]
{
_id: "5db57a03faf1f8434098ab01",
name: "tagA",
slug: "tag-a",
tutorials: [ "5db579f5faf1f8434098f123", "5db579f5faf1f8434098f456" ]
}
// tagB: [Tut #1]
{
_id: "5db57a04faf1f8434098ab02",
name: "tagB",
slug: "tag-b",
tutorials: [ "5db579f5faf1f8434098f123" ]
}
3Sự kết luận
Hôm nay, chúng tôi đã học được nhiều điều về mối quan hệ nhiều-nhiều của MongoDB và thực hiện ví dụ trong ứng dụng Node.js sử dụng Mongoose.
Bạn cũng sẽ biết 3 tiêu chí để chọn tham chiếu hoặc nhúng để cải thiện hiệu suất ứng dụng trong bài viết: MongoDB hướng dẫn mối quan hệ một-nhiều
MongoDB One-to-Many Relationship tutorial with Mongoose examples
Học hỏi! Hẹn gặp lại.
Mã nguồn
Bạn có thể tìm thấy mã nguồn đầy đủ cho ví dụ này trên GitHub.
Đọc thêm
- Tài liệu Mongoose
- Thiết kế mô hình dữ liệu MongoDB
Ứng dụng FullStack Crud: - Mevn: Vue.js + Node.js + Express + MongoDB Ví dụ - trung bình: Angular 8 + Node.js + Express + MongoDB Ví dụ Angular 10 + Node.js + Express + MongoDB Ví dụ Angular 11 + Node.js + Express + MongoDB Ví dụ Angular 12 + Node.js + Express + MongoDB Ví dụ - MERN: React + Node.js + Express + MongoDB Ví dụ
– MEVN:
Vue.js + Node.js + Express + MongoDB example
– MEAN:
Angular 8 + Node.js + Express + MongoDB example
Angular 10 + Node.js + Express + MongoDB example
Angular 11 + Node.js + Express + MongoDB example
Angular 12 + Node.js + Express + MongoDB example
– MERN: React + Node.js + Express + MongoDB example