人口

时间:2017-10-18 16:51:03

标签: node.js mongodb mongoose

我有两个猫鼬模型:

1-活动模特:

eventSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  location: {
    type: { type: String, default: 'Point', required: true },
    coordinates: { type: [Number], required: true },
  },
  sport: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Sport',
    required: true,
  },
  startDate: {
    type: Date,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
  host: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true,
  },
  players: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  }],
}, { timestamps: true });

2-用户模型:

userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
  age: {
    type: Number,
    required: true,
  },
  location: {
    type: String,
  },
}, { timestamps: true });

在我的EventService我尝试按ID找到一个事件并返回填充的sport hostplayers字段。前两个字段在填充和填充时不会抛出任何错误,但问题出在players字段。它抛出了这个错误:

{ MissingSchemaError: Schema hasn't been registered for model "players".
Use mongoose.model(name, schema)
    at MissingSchemaError (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mongoose/lib/error/missingSchema.js:20:11)
    at NativeConnection.Connection.model (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mongoose/lib/connection.js:1043:11)
    at getModelsMapForPopulate (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mongoose/lib/model.js:3569:20)
    at populate (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mongoose/lib/model.js:3113:15)
    at _populate (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mongoose/lib/model.js:3081:5)
    at Function.Model.populate (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mongoose/lib/model.js:3041:5)
    at Immediate.<anonymous> (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mongoose/lib/query.js:1441:17)
    at Immediate.<anonymous> (/Users/elias/Documents/tfg/sporter-app/sporter-api/node_modules/mquery/lib/utils.js:137:16)
    at runCallback (timers.js:781:20)
    at tryOnImmediate (timers.js:743:5)
    at processImmediate [as _immediateCallback] (timers.js:714:5)
  message: 'Schema hasn\'t been registered for model "players".\nUse mongoose.model(name, schema)',
  name: 'MissingSchemaError' }

最后,这就是我调用.populate()方法的方式:

const event = await Event.findById(eventId)
  .populate('sport', 'host', 'players')
  .exec();

知道我做错了什么吗?谢谢!

1 个答案:

答案 0 :(得分:3)

试试这个:

> df$Filename %>% str_extract("\\d{4}_?\\d{2}_?\\d{2}(?=\\.csv)")
[1] "20170930"   "2016_06_13"

此处的文档中有填充多个路径部分: http://mongoosejs.com/docs/populate.html