编辑/答案:这在mongoose> = 3.0中工作正常
我有一个类似的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
我将“零件”添加到车辆中:
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
似乎有效:
{ "_id" : ObjectId("5027bd4340b00b897a000002"), "body" : "car", "fuel" : "unleaded", "make" : "stackover", "model" : "modelname", "parts" : [ ObjectId("5027bd5140b00b897a000006") ], "transmission" : "manual", "year" : 21212 }
但是当我尝试填充部件时:
Vehicle.Model
.findById(vehicle_id)
.populate('parts')
.exec (err, doc) ->
if err
console.error err
else
console.error doc
我收到错误:
TypeError: Property 'model' of object { parts: [] } is not a function at model.populate [as _populate]
是什么给出的?我有另一个模型/控制器组合,几乎是这个完美工作的副本(我几乎找到/替换名词,它仍然打破,严重吓坏了!)
答案 0 :(得分:3)
我认为很可能在内部使用名称“model”,而VehicleSchema的定义正在破坏mongoose希望成为具有“String”类型的函数的东西。
答案 1 :(得分:2)
架构中parts
的定义很容易。 refs
ref:
不应该parts: [ { type: ObjectId, ref: "Part" } ]
?
{{1}}