我正在SailsJS中工作,我試圖爲我的移動應用程序構建一個REST API後端,以允許Newsfeed路徑,這樣如果我查詢JSON前端我可以從www.website.com/user/id/Newsfeed獲得。控制器獲取每個用戶的朋友和他們的帖子,並按照時間順序在該路線上以JSON顯示它。我來自客觀的C背景,所以請耐心等待我的新手。如何查詢特定路線的其餘API的朋友帖子
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});
}
});
}
};
這給了我一個錯誤:throw new Error('嘗試將集合屬性關聯到沒有'+'的模型'+ –
你能發佈整個錯誤嗎?如果它不符合要求這裏只是測試了新的安裝模式代碼,它並沒有給我任何錯誤 –
對不起,它說:[TypeError:無法讀取屬性'id'undefined]。我相信它發生在var userId = req .session.id.friends; line。非常感謝Frederick的幫助! –