V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐工具
RoboMongo
推荐书目
50 Tips and Tricks for MongoDB Developers
Related Blogs
Snail in a Turtleneck
Chan66
V2EX  ›  MongoDB

mongoose 外键查询问题

  •  1
     
  •   Chan66 · 2022-10-11 14:40:42 +08:00 · 1361 次点击
    这是一个创建于 555 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有两个表,一个用户表,一个订单表,现在想要查询所有 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,
        }
    });
    
    2 条回复    2022-10-11 18:45:19 +08:00
    dreasky
        1
    dreasky  
       2022-10-11 15:05:00 +08:00
    aggregate $lookup
    leopod1995
        2
    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 }})
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3773 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 00:15 · PVG 08:15 · LAX 17:15 · JFK 20:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.