javascript - 发送2个数组以在sails js中查看

标签 javascript sails.js

我是 sails.js 的新手,当我尝试通过制作一个简单的 Web 应用程序来学习它时,我遇到了一个问题。我的应用程序是关于类(class)管理的。我的模型有 3 个表:学生、类(class)和列表。学生表保存学生的信息,类(class)表保存类(class)的信息。 list.table 保存有关哪个学生在类(class)中、他们的分数、他们在该类(class)中的缺勤天数的信息。我使用了 res.view(),它适用于任何需要一个数组的 View 。但是,当我尝试编写需要来自 2 个模型:学生和类(class)的信息的函数时, res.view() 没有帮助(或者我不知道如何正确执行)

module.exports = {
   'new': function(req, res, next) {
   Course.find(function foundCourses (err, courses) {
     if (err) return next(err);
     res.view({courses: courses});
   });
   /* Student.find(function foundStudents (err, students) {
     if (err) return next(err);
     res.view({
       students: students
     });
   }); */
   },
   //more other code here
};

在那里,我想发送两个数组来查看,但我不知道如何。如果我愿意的话,Sails.js 只允许我发送一个数组。请帮我 。非常感谢!

最佳答案

您不能调用 res.view 两次。您需要先收集所有数据,然后将其发送以查看。

2种方法:

module.exports = {
    'new': function(req, res, next) {
         var foundCourses = function (err, courses) {
             if (err) return next(err);
             Student.find(function foundStudents (err, students) {
                 if (err) return next(err);
                 res.view({
                     courses: courses,
                     students: students
                 });
             });
         });

         Course.find(foundCourses);
    },
    //more other code here
};

或者您可以使用async.parallel

module.exports = {
    'new': function(req, res, next) {
        var dataCallback = function (err, data) {
            if (err) return next(err);
            var courses = data[0];
            var students = data[1];
            res.view({
                courses: courses,
                students: students
            });
        };

        async.parallel([
            function(callback) {
                Course.find(callback);
            },
            function(callback) {
                Student.find(callback);
            }
        ],dataCallback);
    },
};

关于javascript - 发送2个数组以在sails js中查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40252260/

相关文章:

javascript - Sails.js req.files 为空且 req.body.image 未定义

node.js - sails.js View 未加载

javascript - Mongoose 和字段类型 - 数字返回对象,字符串返回字符串?

javascript - winston 记录器未序列化 mongodb.ObjectID

javascript - 如何获取子id并在其下绘制svg

javascript - 如何将变量从我的 Controller 传递到 HTML,然后传递到 JS 函数?

javascript - 将窗口移动到顶部时出现问题

javascript - SailsJS 和全局函数、变量

mongodb - 使用远程 Mongo DB 时无法加载 Sails

node.js - 在哪里访问和存储 EJS Helpers - SailsJS