mongoose无需查询即可获取相关数据

时间:2018-01-13 04:23:30

标签: javascript node.js mongodb mongoose

我有两个架构,水果架构和用户架构。我将它们拆分为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我只是加入。

2 个答案:

答案 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)

MongoDB提供$ lookup来连接两个集合中的记录:

在您的情况下,您可以使用$lookup加入水果和用户:

db.fruits.aggregate([
   {
     $lookup:
       {
         from: "fruits",
         localField: "buyer",
         foreignField: "_id",
         as: "buyer_info"
       }
  }
])

$lookup在3.6中变得更强大(如果您使用3.6),它允许添加表达式以及您从正确的集合中加入的内容