【问题标题】:How do I connect my mongoDB schema/models?如何连接我的 mongoDB 模式/模型?
【发布时间】:2021-03-13 21:41:33
【问题描述】:

我是新手,正在尝试设置我的 noSQL DB 模型并且正在苦苦挣扎。目的是“场地”可以创建活动(与场地相关),“艺术家”可以匹配并随后计划活动。如果您是艺术家,您还可以查看仪表板并查看您参加过的活动,因此我需要将艺术家连接到场地/活动,但不知道如何。

下面是我的场地模型。它在我的应用中运行良好,但我在哪里添加艺术家?

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const VenueSchema = new Schema({
    title: String,
    image: String,
    price: Number,
    description: String,
    location: String
});

module.exports = mongoose.model('Venue', VenueSchema);

下面是我的艺术家模型。我还没有测试过这个,但我认为它可以正常工作。

const mongoose = require('mongoose');
const { Schema } = mongoose;

const artistSchema = newSchema({
    name: {
        type: String,
        required: [true, 'Artist must have a name']
    },
    genre: {
        type: String
    },
    email: {
        type: String,
        required: [true, 'Contact email required']
    },
})

除了艺术家和地点之外,我希望“事件”包含属性“时间”和“日期”。但是,我不知道在哪里将事件放入模型中。如何连接两个模型之间的“事件”?

【问题讨论】:

    标签: javascript node.js mongodb mongoose-schema


    【解决方案1】:

    我会这样设计

    Venue 架构(与您的相同):所有场地都可以独立于活动和艺术家进行维护。

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    const VenueSchema = new Schema({
      title: String,
      image: String,
      price: Number,
      description: String,
      location: String
    });
    
    module.exports = mongoose.model('Venue', VenueSchema);
    

    Artist 架构(与您的相同):所有艺术家都可以独立于活动和场地进行维护。

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    const artistSchema = newSchema({
      name: {
        type: String,
        required: [true, 'Artist must have a name']
      },
      genre: {
        type: String
      },
      email: {
        type: String,
        required: [true, 'Contact email required']
      },
    })
    
    module.exports = mongoose.model('Artist', artistSchema);
    

    Events schema:这是艺术家和场地聚集的地方。由于活动会持续进行操作(例如更新进度),因此可以独立于艺术家和场地进行操作。

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    const eventSchema = new Schema({
      venue_id: {
        type: Schema.Types.ObjectId,
        ref: 'Venue',
        index: true
      },
      artist_id: {
        type: Schema.Types.ObjectId,
        ref: 'Artist',
        index: true
      },
      created: {
        type: Date,  // Captures both date and time
        default: Date.now
      }
    });
    
    module.exports = mongoose.model('Event', eventSchema);
    

    【讨论】:

    • 啊,然后事件模式将它们联系在一起。我喜欢这个主意。感谢您的反馈!!!
    猜你喜欢
    • 2020-07-10
    • 2018-11-05
    • 2018-07-10
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 2017-08-14
    相关资源
    最近更新 更多