【问题标题】:How to Query Friends Posts In Rest API for a specific Route如何在 Rest API 中查询特定路由的好友帖子
【发布时间】:2016-02-15 09:21:24
【问题描述】:

我在 SailsJS 工作,我正在尝试为我的移动应用程序构建一个 REST API 后端,它允许新闻源路径,这样如果我在前端查询 JSON,我可以从 www.website 获取所有信息.com/user/id/Newsfeed。控制器在哪里获取每个用户的朋友和他们的帖子,并在该路由上按时间顺序以 JSON 格式显示。我来自 Objective-C 背景,所以请容忍我的新手。

config/routes.js

module.exports.routes = {

  '/': {
    view: 'homepage'
  },

    'get /user/:id/newsfeed': {
    controller: 'UserController',
    action: 'newsfeed'
  }

};

Model/User.js

var User = module.exports = {
    //User attributes
    attributes: {
        facebookId: 'string',
        accessToken: 'string',
        location: 'string',
        email: 'string',
        first_name: 'string',
        last_name: 'string',
        about: {
            interests: 'string',
            goals: 'strings',
            headline: 'string',
            birthday: 'date'
        },
        friends : {
            type: 'json'
        },
        posts: {
            collection: 'posts',
            via: 'user'
        },
        picture: 'string'
    }   
};

controllers/UserControllers.js

module.exports = {

    newsfeed: function(req, res) {
        var userId = req.session.id.friends;
        sails.log("Searching for user's friends: "+ userId);

        User.find({ where: { userId: { equals: userId}}}).exec(function(err, records) {
            if(records && records.length == 0) {
                sails.log("No friends found for user:" + userId);
                sails.log(err);
                return res.json(404, "No Friends Found :'(, you'll have alot soon!  You're too cool not to.");
            } else {
                var friendsPostsArray = [];
                    for (i = 0; i < records.length; i++) {
                        var friendsPosts =records[i].posts;
                        friendsPostsArray.push(friendsPosts);
                    }
                var uniquePosts = friendsPostsArray.filter(function (item, i , ar) {
                    return ar.indexOf(item) === i;
                });
                uniquePosts.sort();
                sails.log(uniquePosts);
                sails.log("Returning" + records.length + "friends found for user:" + userId);
                return res.json(200, {friends: records, posts: uniquePosts});

            }
        });
    }
 };

【问题讨论】:

    标签: json node.js rest sails.js sails-mongo


    【解决方案1】:

    似乎您应该将朋友存储为模型中的用户集合:

    friends: {
      collection: 'user',
      via: 'id'
    }
    

    然后在您的控制器中,用他们的朋友和帖子填充您的查询,如下所示:

    newsfeed: function (req, res) {
      var userId = req.param('id');
      sails.log("Searching for user's friends: " + userId);
    
      User.find({ userId: userId })
        .populate('friends')
        .populate('posts')
        .exec(function (err, found) {
          /* Now we have a list of friends, we can find their posts */
          User.find({ userId: found.friends })
            .populate('posts')
            .exec(function (err, found) {
              /* Process friends posts here */
            });
        });
    }
    

    编辑:添加了填充朋友帖子所需的代码。

    【讨论】:

    • 这给了我一个错误: throw new Error('尝试将集合属性关联到没有' + 的模型
    • 你能发布整个错误吗?如果它不适合这里。刚刚在全新安装时测试了模型代码,它没有给我任何错误
    • 对不起,它说:[TypeError: Cannot read property 'id' of undefined]。我相信它发生在 var userId = req.session.id.friends;线。非常感谢弗雷德里克的帮助!
    • 当我转到 localhost:/user/:id/newsfeed 时,它给出了内部服务器错误 500。
    【解决方案2】:

    结果证明是 Frederick 的回答和另一位朋友的一些 tweeking 的结合。

     newsfeed: function (req, res) {
      var userId = (req.param('id'));
      sails.log("Searching for user's friends: " + userId);
    
      User.find({ id: userId })
        .populate('friends')
        .populate('posts')
        .exec(function (err, found) {
    
          if (err) return res.status(err).json(400);
            res.json(200, {found});
    
        });
      }
    

    但它还没有完全完成,因为这只是返回一个朋友列表和 :id 用户的帖子。我使用param 而不是session 并更改了find() 部分,所以我不知道我是否可以给Frederick 的绿色支票,但肯定有我的赞成票。希望这对任何低级程序员有帮助!

    【讨论】:

    • 你应该得到绿色的肉汤。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 2014-12-11
    • 2013-02-07
    相关资源
    最近更新 更多