在開發内容管理系統時,經常會用到多表關聯查詢場景,如文章分類、文章詳情、文章作者三張表,UML圖如下:

業務需求如下:查詢文章資訊,并顯示文章的分類以及文章的作者資訊。這樣簡單的一個需求在MySQL裡要寫一個很長的大SQL語句,但是在MongoDB裡,憑借着Mongoose卻可以輕松實作,實作步驟如下:
1. 定義文章分類的schema生成模型導出,檔案名 aritcleCate.js
// 引入自定義的資料庫連接配接檔案
var mongoose = require('./db.js');
var ArticleCateSchema = new mongoose.Schema({
title: {
type: String,
unique: true
},
descripton: String,
addtime: {
type: Date
}
});
module.exports = mongoose.model('ArticleCate', ArticleCateSchema, 'articlecate');
複制
2. 定義使用者的schema生成模型導出,檔案名 user.js
// 引入自定義的資料庫連接配接檔案
var mongoose = require('./db.js');
var UserSchema = new mongoose.Schema({
username: {
type: String,
unique: true
},
password: String,
name: String,
age: Number,
sex: String,
tel: Number,
status: {
type: Number,
default: 1
}
});
module.exports = mongoose.model('User', UserSchema, 'user');
複制
3. 定義文章的schema生成模型導出,檔案名article.js
// 引入自定義的資料庫連接配接檔案
var mongoose = require('./db.js');
var ArticleSchema = new mongoose.Schema({
title: {
type: String,
unique: true
},
// 分類 id
cid: {
type: Schema.Types.ObjectId
},
// 使用者 id
author_id: {
type: Schema.Types.ObjectId
},
author_name: {
type: String
},
descripton: String,
content: String
});
module.exports = mongoose.model('Article', ArticleSchema, 'article');
複制
4. 執行查詢操作
// 引入定義的文章模型
var ArticleModel = require('./model/article.js');
// 三個表關聯查詢
ArticleModel.aggregate([
{
$lookup: {
from: "articlecate",
localField: "cid",
foreignField: "_id",
as: "cate"
}
},
{
$lookup: {
from: "user",
localField: "author_id",
foreignField: "_id",
as: "user"
}
}
], function (err, docs) {
console.log(JSON.stringify(docs));
})
複制
看到這裡你可能覺得執行這樣一個查詢操作需要定義三個schema來完成,盡管如此,但是這三個schema 卻是獨立的,可以執行單獨的操作,還可以在其他的地方進行複用,也便于進行維護。