如何解决猫鼬中的动态模型关系
我的mongodb Express应用程序中具有以下模型/模式。第一个用于事件:
const eventSchema = new Schema({
title: {
type: String,required: true
},description: {
type: String,price: {
type: Number,date: {
type: Date,createdBy: {
type: Schema.Types.ObjectId,ref: 'User'
}
});
第二个是针对用户的:
const userSchema = new Schema({
email: {
type: String,password: {
type: String,createdEvents: [
{
type: Schema.Types.ObjectId,ref: 'Event'
}
]
});
当我列出事件时,我想获取创建事件的用户的详细信息。现在,我正在使用findById()方法来获取用户并将该用户数据添加到结果中。在列出用户时遵循相同的操作。有没有一种方法可以实现,而无需编写嵌入文档等代码?请让我知道。
谢谢
解决方法
您可以使用填充方法
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
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。