2017-11-25 57 views
1

用戶模式:貓鼬連接兩個不同的集合與不同的外鍵

博客模式

{ 
 
    title: "_title", 
 
    _id: "_mongodbID", 
 
    author: "random_30_characters_string" 
 
    ... 
 
}

Blogs.author是與Users.id相同的ID

而我正試圖做的是當我使用Blogs.findOne()來獲取一些博客文章時,Mongoose也將幫助我獲取一些用戶數據。

而且我已經成功地做到了這一點與原蒙戈shell命令

db.blogs.aggregate([ 
 
    { 
 
    $lookup: { 
 
     from: "users", 
 
     localField: "author", 
 
     foreignField: "id", 
 
     as: "author" 
 
    } 
 
    } 
 
])

我嘗試貓鼬populate方法,但它並沒有爲我

+0

我相信我做了,在這個問題的頂部 –

回答

5

讓工作了肯定博客架構就像

author:{ 
    type:Schema.Types.ObjectId, 
    ref: 'Users' 
} 

和填充像下面

Blogs.findAll({}) 
.populate({ 
    path:author 
}) 
.exec((err, blogs)=>{ 
    console.log(err,blogs); 
})) 

更多信息檢查官方文檔