jacko
jacko

Reputation: 131

meanjs find results for crud module by userid

Total newbie to meanjs, used the yo generator-meanjs to create a project, then used the CRUD Module Sub-Generator to add a CRUD module called Pets. In this particular case I want a user who has signed up on the site to add pets that they own so like petname: 'Woff', pettype: 'dog' etc. This all works great but when I log in as a another user and go to the Pets list - I see the pets added by other users - so just a listing of all the pets whereas what I want is for users to see only the pets they added. I started looking around at how I can achieve this and I see that after authentication that the user_id of the logged on user is held in $scope.authentication.user._id and that the pets module I added included a user property which is assigned the value of the user that created the pet entry. I'm a bit confused of next steps though I figured it would probably involve adding a route and a controller method under the public folder created for the pets CRUD module but I'm not really sure so I thought I'd reach out and ask anyone if they've done this and if so could you list out the steps involved?

Upvotes: 3

Views: 435

Answers (1)

yass
yass

Reputation: 1086

If what you want is to show to each user only the object (pets) he created, you can avoid adding a new route or a controller method, you can just modify the mongoose query that gets all the pets objects, that will be in: app\controllers\pets.server.controller.js, you should modify the create method to be something like:

exports.list = function(req, res) {
    Pet.find({'_user':req.user._id}).sort('-created').populate('user', 'displayName').exec(function(err, pets) {
        if (err) {
            return res.status(400).send({
                message: errorHandler.getErrorMessage(err)
            });
        } else {
            res.jsonp(pets);
        }
    });
};

so its simply just to add the properties you want to search with and the wanted values as a JSON object as a parameter to mongoose find() method.

Upvotes: 3

Related Questions