【问题标题】:Mongoose cannot do deep populateMongoose 无法进行深度填充
【发布时间】:2018-12-12 19:44:42
【问题描述】:

我已经:

  1. User 模型(来自UserSchema
  2. Specialty 模型(来自SpecialtySchema
  3. Session 模型(来自SessionSchema

用户有参考字段specialities

specialities: [{ type: Schema.Types.ObjectId, ref: 'Specialty' }]

会话有引用字段provider

provider: { type: Schema.Types.ObjectId, ref: 'Session' }

我想获取具有填充provider(用户)和深度填充specialities 的会话列表,而不是provider

我正在做以下事情:

Session
  .find()
  .populate({
    path: 'provider',
    model: 'User',
    populate: {
      path: 'specialities',
      model: 'Specialty',
    }
  })

但是结果总是返回一个 IDS 数组(当我尝试通过 provider.specialities 而不是填充版本访问它们时。

专业是关键字吗?

我不知道为什么它就像根本没有填充。

【问题讨论】:

  • 请粘贴您的架构
  • 深度人口在哪里?只需mongoose.model('User').findById(id here).populate('specialities')...等等...
  • 我认为 mongoose 版本 4 的病房可以像这样深入填充? .populate({ path: 'provider', model: 'User', populate: { path: 'specialities', model: 'Specialty', } })
  • @num8er 适用于正常人群,但是当我尝试深入填充 Session 模型的提供者的专业时它不起作用
  • @DarkArtistry 你可以在你try to deep populate a Session model's provider's specialities 的地方添加你的代码吗?

标签: node.js mongoose mongoose-schema mongoose-populate


【解决方案1】:

快速解决方案是使用mongoose-deep-populate

在每个架构中将其作为插件附加:

const deepPopulate = require('mongoose-deep-populate')(mongoose);
SessionSchema.plugin(deepPopulate, {
  whitelist: ['provider', 'provider.specialities']
});

然后像这样使用它:

const Session = mongoose.model('Session');
cons user = await Session.findById(id here)
                         .deepPopulate(['provider', 'provider.specialities']);



由于可能存在性能问题,我不建议进行深度填充。

最好尝试重新思考您的数据。

我也无法想象它的用例。

也许您只是想显示具有特长的用户列表?

从前端调用 2 个 api 怎么样:

1st for taking sessions and taking provider ids (ex.: GET /sessions), 

2nd for taking users with populated specialities (ex.: GET /users?ids=first-id,second-id...)

或:

let sessions = await Session.find();
let providerIds = sessions.map(session => session.provider);
let users = await User.find({_id: providerIds}).populate('specialities');

sessions = sessions.map(session => {
  session.provider = users.find(user => user._id == session.provider);
  return session;
});

【讨论】:

  • 我将使用该解决方案而不需要额外的库,谢谢
猜你喜欢
  • 2017-07-06
  • 1970-01-01
  • 2017-09-15
  • 2022-01-21
  • 2017-05-06
  • 2015-10-12
  • 2017-03-23
  • 2020-12-08
  • 2017-04-08
相关资源
最近更新 更多