我有两个架构,水果架构和用户架构。我将它们拆分为2个不同的集合,但是水果架构可以引用用户。
const FruitSchema = new Schema({
title: {
type: String
},
buyer: {
_id: {
type: Schema.Types.ObjectId,
default: null
}
}
})
const UserSchema = new Schema({
name: {
type: String
},
age: {
type: Number
},
gender: {
type: String
}
})
您如何使用用户信息查询所有水果?我能想到的是找到所有水果,找到买家。然后找到每个用户,将它们映射回水果阵列,听起来如此繁琐复杂。如果是mysql我只是加入。
答案 0 :(得分:2)
您需要使用export default class Search extends Component {
static async getInitialProps({ query: { location } }) {
let res
if (process.env.MY_ENVIRONMENT === 'development') {
res = await fetch(
`http://localhost:3000/api/search?location=${location}`
)
} else if (process.env.MY_ENVIRONMENT === 'production') {
res = await fetch (
`https://productionurl.now.sh/api/search?location=${location}`
)
}
const businesses = await res.json()
return businesses
}
...
}
来加入带有用户ID的买方ID,对于所有匹配的集合,它会将用户信息作为嵌入文档返回
$lookup
水果收集
db.fruitz.aggregate(
[
{
$lookup : {
from : "userz",
localField : "buyer_id",
foreignField: "_id",
as : "buyerInfo"
}
}
]
)
用户集合
> db.fruitz.find().pretty()
{ "_id" : 2, "title" : "apple", "buyer_id" : 1 }
{ "_id" : 1, "title" : "banana", "buyer_id" : 2 }
$ lookup aggregate
> db.userz.find().pretty()
{ "_id" : 1, "name" : "abc", "age" : 20, "gender" : "M" }
>
输出
> db.fruitz.aggregate( [ { $lookup : { from : "userz", localField : "buyer_id", foreignField: "_id", as : "buyerInfo" } } ] ).pretty()
答案 1 :(得分:1)