【问题标题】:How to have relate two collections that have a one-to-one relationship如何关联两个具有一对一关系的集合
【发布时间】:2018-01-19 15:44:45
【问题描述】:

我在 NoSQL 数据库方面的经验为 0,很难不为这个问题想出一个“SQL 解决方案”。我有一家餐厅,显然有地址。我的第一个想法是简单地放置很多字段,例如国家、城市、邮编、line1 等……但是我认为将其引用到地址文档,让我可以灵活地轻松更改地址的结构,所以在一点点研究我想出了这个:

var RestaurantSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    address: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Address',
        required: true
    },
    // a few more fields
    createdAt: {type: Date, default: Date.now},
    updatedAt: {type: Date, default: Date.now},
});

var AddressSchema = new mongoose.Schema({
    restaurant: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Restaurant'
    },
    line1: {
        type: String,
        required: true
    },
    line2: {
        type: String,
    }
    // etc
    createdAt: {type: Date, default: Date.now},
    updatedAt: {type: Date, default: Date.now},
});

我的问题是在想知道如果我想从一个城市中检索所有餐馆之后该怎么做,例如,我会执行 find('Houston') 之类的操作,然后从 Addresses 引用的每个 id 中获取每个 Restaurant找回来了?

我觉得有更好的方法可以做到这一点,但目前我什至不知道还要搜索什么来寻找答案。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以像这样制作您的地址架构

    var AddressSchema = new mongoose.Schema({
        restaurant: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Restaurant'
        },
        city: {
            type: String,
            required: true
        },
        line1: {
            type: String,
        }
        // etc
        createdAt: {type: Date, default: Date.now},
        updatedAt: {type: Date, default: Date.now},
    });
    

    问题:如果我想检索一个城市的所有餐馆,我会怎么做?

    Ans:为此,您可以使用 populate of moongose

    例如:

    var addressModule=require('addressSchema')
    addressModule.find({city:'Houston'}).populate({'path':'restaurant','model':'restaurantSchema'})
    

    结果:

    [
    {
      restaurant:{
          name:"ABC",
          address:"123"
         },
      city:"Houston",
      line1:"xxx"
    },
    {
      restaurant:{
          name:"DEF",
          address:"233"
         },
      city:"Houston",
      line1:"xxx"
    }
    ]
    

    【讨论】:

      猜你喜欢
      • 2021-05-08
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多