使用nodejs中的其他模型数据填充表单中的下拉列表

我想填充一个表格为我的模型(汽车),从另一个模型(颜色)的数据下拉列表,但似乎无法弄清楚如何做到这一点。 我需要以不同的方式调用cars.jade文件中的下拉列表中的颜色,以便当用户select自动填充列表时,我需要ObjectID作为项目的值(随后保存为新车。

汽车新forms(car.jade):

/* This is the bit I'm having trouble with */ select(name='carColours') option(value='') each colour in colours - var select=null; if (colour.title == carColours.title) select='selected'; option(value=colour._id, selected=select)= colour.title 

汽车控制器(cars.js):

 exports.new = function(req, res){ res.render('cars/new', { title: 'New Car', event: new Car({}) }) } 

汽车模型(car.js):

 var CarSchema = new Schema({ title: {type : String, default : '', trim : true}, colour: {type : Schema.ObjectId, ref : 'Colour'}, }) 

颜色模型(colour.js)

 var ColourSchema = new Schema({ title: {type : String, default : '', trim : true}, hexadecimal: {type : String, default : '', trim : true}, }) ColourSchema.statics = { list: function (options, cb) { var criteria = options.criteria || {} this.find(criteria) .sort({'title': 1}) // sort alphabetically .exec(cb) } } 

您在car.js中呈现的调用需要提供颜色列表。

 exports.new = function(req, res){ res.render('cars/new', { title: 'New Car', event: new Car({}), colours: [<list of possible colours>] }) } 

在视图模板path之后传递的对象是视图模板运行的上下文。 如果该对象没有问题的属性(在这种情况下colours ),那么您的视图模板也不会。 (有一个例外,但它看起来不像你在这里使用它)。

我在我制作的一个截屏video系列的最后一集中进入了这个video。( http://www.learnallthenodes.com/episodes/9-view-templates-in-nodejs-with-jade ) 我不确定当我打那个部分的确切时间戳。