Meanjs find results for crud module by userid

For all newbies to meanjs, used the yo generator generator to create the project, and then used the CRUD module Sub-Generator to add a CRUD module called Pets. In this particular case, I want the user who signed up on the site to add the pets they own, just like petname: "Woff", pettype: "dog", etc. This all works great, but when I log in as a different user and go to the Pets list - I see pets added by other users, so just a list of all pets, whereas I want users to see only pets which they added. I started pondering how I can achieve this, and after being authenticated, the user_id of the logged in user is in $ scope.authentication.user._id and that the pets module I added includes a user property that is assigned the value of the user who created the pet entry. I'm a little confused about the next steps, although I suppose it probably has to do with adding a route and controller method in the shared folder created for the pet CRUD module, but I'm not entirely sure, so I thought I'd get to you and ask anyone if they did it and if so can you please indicate these steps?created for the CRUD module for pets, but I'm not entirely sure, so I thought I'd reach you and ask someone if they did, and if so can you point out those steps?created for the CRUD module for pets, but I'm not entirely sure, so I thought I'd reach you and ask someone if they did, and if so can you point out those steps?

+3


source to share


1 answer


If you only want to show each user only the object (pets) that he created, you can avoid adding a new route or controller method, you can simply change the mongoose query that will get all the pet objects that will be in: app \ controllers \ pets.server.controller.js , you should change 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 just add the properties you want to search for and the values ​​you want as a JSON object as a parameter to the mongoose find () method.

+3


source







All Articles