如何查询朋友post在特定路线的Rest API中

我正在SailsJS工作,我正在尝试为我的移动应用程序构build一个REST API后端,以允许Newsfeedpath,所以如果我在前端查询JSON,我可以从www.website.com/用户/ ID /新闻源。 控制器获取每个用户的朋友和他们的post,并按照时间顺序显示在该路线上的JSON。 我来自一个客观的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}); } }); } }; 

好像你应该把朋友存储为模型中的用户集合一样:

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

而在你的控制器中,用他们的朋友和post来填充你的查询,如下所示:

 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 */ }); }); } 

编辑:添加需要填充朋友post的代码。

答案结果是弗雷德里克的答案和另一个朋友的一些推特。

  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用户的post。 我用param而不是session并改变了find()部分,所以我不知道我是否能给弗雷德里克的荣耀的绿色检查,但肯定有我upvote。 希望这可以帮助任何低级别的编程人员!