猫鼬用不同的外键加入了两个不同的集合 [英] Mongoose join two different collections with different foreign key
本文介绍了猫鼬用不同的外键加入了两个不同的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
用户架构:
{
username: "milkeypony",
_id: "_mongodbID",
id: "random_30_characters_string"
...
}
博客架构
{
title: "_title",
_id: "_mongodbID",
author: "random_30_characters_string"
...
}
Blogs.author
与Users.id
我想做的是当我使用Blogs.findOne()
来获取一些博客文章时,Mongoose还将帮助我获取一些用户数据.
And what I'm trying to do is when I use Blogs.findOne()
to fetch some blog post, Mongoose will also help me fetch some user data.
我已经用原始的Mongo shell命令成功完成了此操作
And I already successfully done this with raw Mongo shell command
db.blogs.aggregate([
{
$lookup: {
from: "users",
localField: "author",
foreignField: "id",
as: "author"
}
}
])
我尝试了猫鼬populate
方法,但是对我来说效果不佳
And I try the mongoose populate
method, but it didn't work out for me
推荐答案
确保Blog架构具有
author:{
type:Schema.Types.ObjectId,
ref: 'Users'
}
并像下面一样填充
Blogs.findAll({})
.populate({
path:author
})
.exec((err, blogs)=>{
console.log(err,blogs);
}))
更多信息,请查看官方文档
more info check offical doc
这篇关于猫鼬用不同的外键加入了两个不同的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文