节点js - 如何填充多个"选择"使用Mongoose控制

时间:2014-03-26 22:55:49

标签: node.js mongodb express mongoose

我在快递js中有一个项目,我正在使用mongoose,我可以用以下内容填充选择控件:

app.get('/new_alumno', alumno.create);

但现在我想填充多个选择控件,但我不知道如何从我的控制器向我的视图发送两个以上的值。

我的app.js文件包含以下代码

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

//Reference to the controllers
var alumno = require('./controllers/ctrl_alumno');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

//Routes
app.get('/', routes.index);    
app.get('/alumnos', alumno.listalumnos);
app.get('/new_alumno', alumno.create);
app.post('/save_alumno', alumno.save);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

我的控制器ctrl_alumno.js包含以下代码:

// Crear conexion con MongoDB
var mongoose = require('mongoose');
var db_link = 'mongodb://localhost/alumnosnormalized';
var db = mongoose.createConnection(db_link);

// Variables para cargar el modelo
var alumno_schema = require('../models/alumno');
var carrera_schema = require('../models/carrera');
var entidad_schema = require('../models/entidad');

var Alumno = db.model('Alumno', alumno_schema);
var Carrera = db.model('Carrera', carrera_schema);
var Entidad = db.model('Entidad', entidad_schema);

exports.create = function(req, res, next){

    Carrera.find(getCarreras);

    function getCarreras(err, carrera){
        if(err)
        {
            console.log(err);
            return next();
        }
        return res.render('newalumno',{title:'Lista de alumnos', carreras: carrera});   
    };
};

我的学生视图包含以下代码:

block content
    h1= title
    div(class="form_settings")
        h2 Ingrese la informacion necesaria para registrar una Entidad
        form#formAddPlayer(name="addalumno",method="post",action="/save_alumno")
            p
                input#inputNombre(class="contact", type="text", placeholder="Nombre del Alumno", name="nombreAlumno")
            p
                input#inputApaterno(class="contact", type="text", placeholder="Apellido Paterno", name="aPaterno")
            p
                input#inputAmaterno(class="contact", type="text", placeholder="Apellido Materno", name="aMaterno")
            p
                select(name="idCarrera")
                    option(value="",selected="selected") Seleccione un elemento de la lista
                    each item, i in carreras                    
                        option(value='#{item._id}') #{item.descripcion}                         
            p
                button#btnSubmit(class="submit", type="submit") Guardar Alumno

我只能使用此代码填充单个选择控件,它可以正常工作。

<select name="idCarrera">
    <option value="" selected="selected">Seleccione un elemento de la lista</option>
    <option value="5330a2a7ab37e2b810000001">Quimica</option>
    <option value="5330a575a20912b013000001">Mecanica</option>
    <option value="5331c63f6ddf2b4c0c000001">Contaduria</option>
</select>

任何人都可以帮助我从控制器传递多个值,或者使用mongoose填充多个选择控件?

1 个答案:

答案 0 :(得分:1)

您可以使用async parallel,然后返回结果数组。 parallel方法采用一组异步函数,它们接受一个回调参数,并返回一个结果数组。您可以根据需要在阵列中添加任意数量的函数。

https://github.com/caolan/async#parallel

例如

async.parallel([
        function(callback) {
            Alumno.find({}, function(err, result){
                callback(err, result);
            });
        },
        function(callback) {
            Carrera.find({}, function(err, result){
                callback(err, result);
            });
        }
    ],
    function(err, results) {
        // Results here will be an array results returned from the database.
        // You can manipulate the results here before returning to the view.
        return res.render('view', {results : results}); 
    });