2016-03-06 64 views
0

很抱歉的模糊冠軍,但我想要做的是以下幾點: 我有2種獴型號:帖子和用戶(可以是帖子的作者)貓鼬Model.find - >編輯 - >回調?

const Post = new Schema({ 
    title: {type: String, required: true, unique: true}, 
    content: {type: String, required: true}, 
    date_created: {type: Date, required: true, default: Date.now}, 
    authorId: {type: String, required: true},    // ObjectId 
    author: {type: Schema.Types.Mixed}, 
    page: {type: Boolean, required: true, default: false} 
}); 

post.find()
貓鼬發送查詢的MongoDB
的MongoDB返回文檔
中間件檢索基礎上,authorId財產筆者
Add找到用戶的帖子author
post.find callback

這可能嗎?

回答

1

是,mongoose document references and population會爲你做到這一點。

const Post = new Schema({ 
    // ... 
    author: {type: mongoose.Schema.Types.ObjectId, required: true, ref: "User"} 
}); 

ref: "User"告訴Mongoose使用「User」類型作爲對象類型。確保你有一個用Mongoose定義的「用戶」模型,否則這將失敗。

加載完整的對象圖,使用查詢的populate方法:


Post 
    .findOne(/* ... */) 
    .populate('author') 
    .exec(function (err, story) { 
    // ... 

    }); 

P.S.我在Screencast Package中涵蓋了這個和更多。

+0

謝謝! 這的確有訣竅! ^^ 代碼現在工作:) '常量體=收率this.Model.find() .populate( 'AUTHORID') .lean();' – CreasolDev