猫鼬中的动态模型关系

时间:2020-09-14 11:10:48

标签: mongodb mongoose relationship mongoose-schema

我的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()方法来获取用户并将该用户数据添加到结果中。在列出用户时遵循相同的操作。有没有一种方法可以实现,而无需编写嵌入文档等代码?请让我知道。

谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用填充方法

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

[编辑]这将为您提供用户事件,如果您想要事件包含用户数据,则应该从相反的方向做同样的事情

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