我是 Node Js 和相关程序的新手。目前正在尝试创建一个应用程序,该应用程序可以上传带有标题等的图像,并供用户喜欢和评论(更像是 instagram/facebook)。到目前为止,我的应用程序可以工作,但现在我试图从多个表中提取多个值,将值作为数组中的对象传递并在新的 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});
});

有没有更简单的方法来解决这个问题?不过我还没有接触过迁移。

最佳答案

    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})

                    })

                })
        })
})

});

此解决方案由以下链接提供:
Querying multiple models with Sequelize.js ORM

关于javascript - Sequelize 从多个表中提取数据并作为对象传递以在 EJS 中呈现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41324800/

10-09 20:27
查看更多