填充时出现Mongoose错误('model'不是函数)

时间:2021-01-12 02:34:13

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

编辑/答案:这也适用于mongoose> = 3.0

I have a mongoose schema that looks like so:

我有一个mongoose架构,看起来像这样:

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!)

是什么赋予了?我有另一个模型/控制器组合几乎是这个完美工作的副本(我几乎找到/替换名词,它仍然打破,严重吓坏了!)

2 个解决方案

#1


3  

I think its likely that the name "model" is used internally, and the definition of VehicleSchema is clobbering something that mongoose expects to be a function with the "String" type.

我认为很可能在内部使用名称“model”,而VehicleSchema的定义正在破坏mongoose希望成为具有“String”类型的函数的东西。

#2


2  

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

模式中部件的定义很容易。不应该参考ref:?

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

#1


3  

I think its likely that the name "model" is used internally, and the definition of VehicleSchema is clobbering something that mongoose expects to be a function with the "String" type.

我认为很可能在内部使用名称“model”,而VehicleSchema的定义正在破坏mongoose希望成为具有“String”类型的函数的东西。

#2


2  

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

模式中部件的定义很容易。不应该参考ref:?

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