编辑/回答: 在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
I get an error:
TypeError: Property 'model' of object { parts: [] } is not a function at model.populate [as _populate]
出了什么问题?我之前有一个几乎和这个一模一样的模型/控制器组合,完美地运作着(我基本上只是替换了名词,但它依然出现了问题,我真的很焦虑!)
model: String
改为car_model: String
,现在一切都完美运行了。谢谢! - Margh