天天看點

使用Mongoose的populate方法實作多表關聯查詢

MongoDB在3.2以上的版本有類似于 join 的 $lookup 聚合操作符,其實 Mongoose 有一個更強大的替代方法,叫做populate ( ),它允許你在其他集合中引用文檔,實作更簡潔優雅的查詢操作。

以内容管理系統為例,有文章分類、文章詳情、文章作者三個集合,UML圖如下:

使用Mongoose的populate方法實作多表關聯查詢

業務需求如下:查詢文章資訊,并顯示文章的分類以及文章的作者資訊,下面用 populate 來實作這個查詢需求。

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

通過給 schema 中的關聯字段添加 ref 與指定的模型建立關聯

// 引入自定義的資料庫連接配接檔案
var mongoose = require('./db.js');
var Schema = mongoose.Schema;

var ArticleSchema = new Schema({
    title: {
        type: String, unique: true
    },
    // 分類ID
    cid: {
        type: Schema.Types.ObjectId,
        // 引用文章分類的模型  
        ref: "ArticleCate"
    },
    // 使用者ID
    author_id: {
        type: Schema.Types.ObjectId,
        // 引用 user 的模型
        ref: "User"
    },
    author_name: {
        type: String
    },
    descripton: String,
    content: String
});


module.exports = mongoose.model('Article', ArticleSchema, 'article');           

複制

4. 執行查詢操作

// 注意使用 populate 需要引入用到的 model
var ArticleCateModel=require('./model/articleCate.js');
var ArticleModel=require('./model/article.js');
var UserModel=require('./model/user.js');

// 文章表、分類表關聯
ArticleModel.find({}).populate('cid').exec(function(err,docs){
    console.log(docs);
})


// 文章表、分類表、使用者表關聯
ArticleModel.find({}).populate('cid').populate('author_id').exec(function(err,docs){
    console.log(docs);
})           

複制

通過給 populate 中傳入所關聯的字段與指定的集合進行關聯查詢,在 exec( ) 的回調方法中擷取查詢的結果。