【问题标题】:dynamic model relations in mongoose猫鼬中的动态模型关系
【发布时间】:2020-09-14 11:10:48
【问题描述】:

我的 mongodb express 应用程序中有以下模型/模式。第一个用于事件:

const eventSchema = new Schema({
  title: {
    type: String,
    required: true
  },
  description: {
    type: String,
    required: true
  },
  price: {
    type: Number,
    required: true
  },
  date: {
    type: Date,
    required: true
  },
  createdBy: {
      type: Schema.Types.ObjectId,
      ref: 'User'
  }
});

第二个是给用户的:

const userSchema = new Schema({
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  createdEvents: [
    {
      type: Schema.Types.ObjectId,
      ref: 'Event'
    }
  ]
});

当我列出事件时,我想获取创建它们的用户的详细信息。现在我正在使用 findById() 方法来获取用户并将该用户数据添加到结果中。在列出用户时遵循同样的事情。有没有办法在不编写嵌入文档等代码的情况下实现这一目标?请告诉我。

谢谢

【问题讨论】:

    标签: mongodb mongoose relationship mongoose-schema


    【解决方案1】:

    你可以使用填充方法

    User.findById(id)
        .populate('createdEvents')
        .then(userWithEvents => {
          ... // use result here
        })
        .catch(err => {
          ... // handle error here
        })
    

    [Edit] 这会给你用户他的事件,如果你想要用户数据的事件,你应该从反面做同样的事情

    Event.find(...)
        .populate('createdBy')
        .then(eventWithUser => {
          ... // use result here
        })
        .catch(err => {
          ... // handle error here
        })
    

    【讨论】:

    • 嵌入文档怎么样?
    • 没有必要将事件嵌入到用户中,如果你这样做,你将拥有另一个数据结构。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2017-03-31
    • 2015-09-16
    • 2017-10-05
    相关资源
    最近更新 更多