mongoose 嵌套查詢之Populate方法使用

  這是我在用Nodejs + express + mongoose 開發一個博客系統的時候遇到的一個問題。首先我定義了三個Schema,以下:express

/*
* comment.js
*/

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = require('./user.js');
var Blog = require('./blog.js');

var Comment = new Schema({
    author: {type: Schema.Types.ObjectId,ref:'user'}, //做者,定義外鍵
    content: {type: String, require:true},   //評論內容
    blog: {type: Schema.Types.ObjectId,ref:'Blog'},
    time : Date,   //評論發佈時間
    recommend: Number
});


module.exports = mongoose.model('comment', Comment);

/*
* user.js
*/

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');

var User = new Schema({
    username: String,
    password: String
});

User.plugin(passportLocalMongoose);

module.exports = mongoose.model('user', User);

/*
* comment.js
*/

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = require('./user.js');var BlogSchema = new Schema({
    title: {type: String, require: true},    //博客標題
    content: {type: String, require: true},    //博客內容
    author: {type: Schema.Types.ObjectId,ref:'User'}, //做者,定義外鍵
    time : Date, //博客發佈時間
    recommend: Number,   //博客被贊次數
    // comment: {type: Schema.Types.ObjectId,ref:'Comment'}            //評論
});


module.exports = mongoose.model('blog', BlogSchema);

  在Comment的Schema定義中,author的類型ObjectId對應User集合中的_id。mongoose

  那麼如今若是要查詢一個評論的做者信息(用戶名)該怎麼處理呢?ui

  若是直接spa

    Comment.findById(req.params.blogId).exec((err,comment) =>{
        if (err) {
            console.log(err);
        } else {
            console.log("做者信息" +comment[0].author);
        }
    });

  輸出的只是做者的_id,若是你不怕麻煩就根據_id去User集合再找一次。code

  那麼怎麼去直接獲取username呢,就要用到Populatele了。blog

 

                    Comment.find({blog:req.params.blogId}).populate('author').exec((err,comments) =>{
                        if (err) {
                            console.log(err);                 
                        } else {
                            console.log("+++++++++",comments[0].author.username);

                        }
                    });

  

 

這麼處理一下就能夠直接使用username了。開發

相關文章
相關標籤/搜索