Reputation: 188
Im really new to MEANJS and after some days of google research i can't find a good way and a good tutorial to learn how to make a kind of articles module (like the one in MEANJS starter) belongs to a user.
At now my crud module work well but all the data is displayed for all users. I just want that the user can add article (here this is have an another name but anyway) and only this user can see this article.
I find your question here and you look like to have achieve a kind of what i'm trying. So if you have any tips or any ressources to help me, i'm up ! Of course i have read the mongoose docs part about population and i'm sure this is it, but alone this is hard. I've already tried to link my users module and article module but don't work.
Thanks for your time man, and have a happy coding day :) Greettings from Paris.
Upvotes: 1
Views: 85
Reputation: 4448
If you check mongodb entry for articles it already holds the user ObjectId that created the article:
> db.articles.find()
{ "_id" : ObjectId("55c7751dbafe1a306b6ce54d"), "user" : ObjectId("55c774f9bafe1a306b6ce54c"), "content" : "My latest test. another info", "title" : "Test", "created" : ISODate("2015-08-09T15:43:25.467Z"), "__v" : 0 }
{ "_id" : ObjectId("55c7c2edd4bc5f277b775ba9"), "user" : ObjectId("55c774f9bafe1a306b6ce54c"), "content" : "ATESTE", "title" : "TESTE", "created" : ISODate("2015-08-09T21:15:25.762Z"), "__v" : 0 }
>
The reason that all articles are loaded when you click "List Articles" menu entry is because the list implementation for articles in articles.server.controller.js does not restrict the find to load only the logged user articles, the default implementation loads all articles from mongodb:
/**
* List of Articles
*/
exports.list = function (req, res) {
Article.find().sort('-created').populate('user', 'displayName').exec(function (err, articles) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(articles);
}
});
};
I've never tried that but I believe the easiest way to do what you want would be to change that call to have a criteria and load only the articles from the logged in user, something like:
/**
* List of Articles
*/
exports.list = function (req, res) {
Article.find({user: req.user}).sort('-created').populate('user', 'displayName').exec(function (err, articles) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(articles);
}
});
};
This, or something like this(I didn't test it) should now bring only the logged in user created articles. Check details of mongoose query here.
Upvotes: 0