简体   繁体   中英

Mongoose Error when Populating ('model' is not a function)

EDIT/ANSWER: this works fine in mongoose >= 3.0 also

I have a mongoose schema that looks like so:

mongoose = require 'mongoose'
ObjectId = mongoose.Schema.ObjectId

VehicleSchema = new mongoose.Schema
  make: String
  model: String
  year: Number
  body: String
  fuel: String
  transmission: String
  parts: [ { type: ObjectId, ref: 'Part' } ]

VehicleSchema.virtual('display_name').get ->
  return this.make + ' ' + this.model + ' ' + this.year

VehicleModel = mongoose.model 'Vehicle', VehicleSchema

module.exports =
  Schema: VehicleSchema
  Model: VehicleModel

I add 'parts' to the vehicle like this:

Vehicle.Model.findById id, (err, vehicle) ->
      unless err
        part = new Part.Model {
          ...details
        }
        part.save (err, doc) ->
          unless err
            vehicle.parts.push doc
            vehicle.save()
          else
            console.error err

which seems to work:

{ "_id" : ObjectId("5027bd4340b00b897a000002"), "body" : "car", "fuel" : "unleaded", "make" : "stackover", "model" : "modelname", "parts" : [ ObjectId("5027bd5140b00b897a000006") ], "transmission" : "manual", "year" : 21212 }

but when I try and populate the parts:

Vehicle.Model
  .findById(vehicle_id)
  .populate('parts')
  .exec (err, doc) ->
    if err
      console.error err
    else
      console.error doc

I get an error:

TypeError: Property 'model' of object { parts: [] } is not a function at model.populate [as _populate]

What gives? I had another model/controller combination that was almost a carbon copy of this that worked perfectly (I've pretty much find/replaced the nouns and it still breaks, seriously freaking out here!)

我认为名称“模型”可能在内部使用,而VehicleSchema的定义正在掩盖猫鼬期望是“字符串”类型的函数的某些东西。

The definition of parts in the schema looks off. Shouldn't refs be ref: ?

parts: [ { type: ObjectId, ref: "Part" } ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM