Sequelize从多个表中提取数据并将其作为对象传递给EJS

对于Node Js和相关的程序来说是新的。 目前正试图创build一个应用程序上传图片与字幕等,并为用户喜欢和评论(更像Instagram /脸书)。 到目前为止,我的应用程序工作,但现在卡在一个点,当我试图从多个表拉多个值,传递值作为数组中的对象,并呈现在一个新的EJS文件。 下面是代码

app.get('/pages/photos/:id', function (req, res){ //show photos with comments //1. photo with id :id // 2. all comments associated with id :id //likes associated with photo var photoId=req.params.id; var photoData = [] Photos.findOne({ where:{id: photoId}, attributes: ['userId','filename', 'caption', 'createdAt'] }).then(function (rowPhoto){ photoData.photoValues = [] var vals = { photoId:photoId, userId:rowPhoto.userId, photoName: rowPhoto.filename, caption:rowPhoto.caption, createdAt:rowPhoto.createdAt } photoData.photoValues.push(vals); console.log("#1 "+ rowPhoto.caption); }).then(function(){ Comments.findAll( {where: {photoId:photoId} }).then(function(rowComments){ photoData.photoComments= [] for (i=0; i < rowComments.length ; i++){ vals = { id: rowComments[i].id, userId: rowComments[i].userId, text:rowComments[i].comment, createdAt:rowComments[i].createdAt } photoData.photoComments.push(vals); } console.log("#2 "+ rowComments.length); }); }).then(function(){ Likes.findAll({ where:{photoId:photoId} }).then(function(rowLikes){ photoData.photoLikes= [] for (i=0; i < rowLikes.length ; i++){ vals = { id: rowLikes[i].id, liked: rowLikes[i].liked, userId:rowLikes[i].userId, photoId:rowLikes[i].photoId } photoData.photoLikes.push(vals); } console.log("#3 " + rowLikes[i]); }); }); console.log("#4 " + photoData); //res.render('views', {views:photoData}); }); 

有没有更简单的方法来解决这个问题? 尽pipe如此,我还没有碰到迁移。

  Photos.findOne({ where:{id: photoId}, attributes: ['id','userId','filename', 'caption', 'createdAt'] }).then(function (rowPhotos){ Comments.findAll({ where: {photoId:photoId} }).then(function (rowComments){ Likes.findAll({ where: {photoId: photoId} }).then(function (rowLikes){ Users.findAll().then(function (commentUser){ var data= { photoData: rowPhotos, commentData: rowComments, likesData: rowLikes, userData:commentUser } console.log(data); res.render('views', {data:data}) }) }) }) }) 

});

这个解决scheme由以下链接礼貌: 查询多个模型与Sequelize.js ORM