mongoose 外键查询问题

2022-10-11 14:40:42 +08:00
 Chan66

有两个表,一个用户表,一个订单表,现在想要查询所有 appId 为 1 的用户的订单应该怎么查询呢

const orderSchema = new mongoose.Schema({
    user: {
        type: mongoose.SchemaTypes.ObjectId,
        ref: "User",
        required: true
    },
    orderNum: {
        type: String,
        required: true
    },
})
const UserSchema = new mongoose.Schema({
    nickname: String,
    avatarUrl: String,
    phone: String,
    appId: {
        type: String,
    }
});
1372 次点击
所在节点    MongoDB
2 条回复
dreasky
2022-10-11 15:05:00 +08:00
aggregate $lookup
leopod1995
2022-10-11 18:45:19 +08:00
最简单的

1. 先查所有 appId 为 1 的用户 id -> userIds = user.find({ appId: 1 }).select('_id')
2. order.find({ user: { $in: userIds }})

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/886074

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX