【问题标题】:Mongoose populate multiples idsMongoose 填充多个 id
【发布时间】:2017-05-12 13:45:18
【问题描述】:

我有这些架构

var DriverSchema = Schema({
  name: String,
  groups: {
     type: String,
     ref: 'DriverGroup'
  }
});


var DriverGroupSchema = Schema({
  name: String
});

module.exports = mongoose.model('DriverGroup', DriverGroupSchema);
module.exports = mongoose.model('Driver', DriverSchema);

我有这些驱动程序组:

[{
  id: '12345',
  name: 'Group1'
}, {
  id: '6789',
  name: 'Group2'
}]

还有这个司机:

{
  name: 'Driver1',
  groups: '12345,6789'
}

如何按人口获取组?我正在使用这个:

Driver.find().sort('name').populate('groups')

但不能正常工作。

【问题讨论】:

    标签: node.js mongodb mongoose population


    【解决方案1】:

    如果您想以这种方式填充 groups,则您存储错误。
    populate 无法解析字符串以确定单独的实体。

    应该是数组

    groups: '12345,6789'
    

    应该是

    groups: ['12345,6789']
    

    此外,通过查找 _ids(不是名称字段)来填充作品

    因此,需要更改您的架构:

    var DriverSchema = Schema({
      name: String,
      groups: [{ type: string, ref: 'DriverGroup' }]
    });
    

    您还需要设置_id(在您的情况下将_id 设置为与name 相同)

    var DriverGroupSchema = Schema({
      _id: String,
      name: String
    });
    

    http://mongoosejs.com/docs/populate.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 2020-12-08
      • 2021-11-03
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 2020-11-04
      相关资源
      最近更新 更多