1

My controller:

@RequestMapping(value = "/{id}/giveFacilitiesAccess", method = RequestMethod.POST)
    public Object giveFacilityAccessToAnotherUser(@PathVariable("id") String userId)
    {
        return userService.giveFacilitiesAccessToAnotherUser(userId);
    }

My service:

@Override
    public Object giveFacilitiesAccessToAnotherUser(String id)
    {
        String userId = getLoggedInUserId();
        User u = userDao.findById(userId);
        List<String> facilitiesAccess = u.getFacilitiesAccess();
        return userDao.giveFacilitiesAccessToAnotherUser(id,facilitiesAccess);

    }

My dao:

@Override
    public Object giveFacilitiesAccessToAnotherUser(String userId, List<String>facilitiesAccess)
    {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(userId));
        Update update = new Update().addToSet("facilitiesAccess.",facilitiesAccess);
        mongoTemplate.updateFirst(query, update, User.class);
        return null;
    }

After updating: "facilitiesAccess":["5f0996f792691d1b68671da3",["5f0998ba92691d1b68671da4"]]

It's updating like array inside another array, but i need in this format:
"facilitiesAccess":["5f0996f792691d1b68671da3","5f0998ba92691d1b68671da4"]

2 Answers 2

1

The update works with the syntax using the addToSet(String key) which returns a Update.AddToSetBuilder - then apply the each(Object... values) method on the builder, to return the Update object.

Update update = new Update().addToSet("facilitiesAccess").each(facilitiesAccess);
Sign up to request clarification or add additional context in comments.

1 Comment

Thnaks now it is adding in array
0

You need to use Each like below

    @Override
    public Object giveFacilitiesAccessToAnotherUser(String userId, List<String>facilitiesAccess)
    {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(userId));
        Update update = new Update().addToSet("facilitiesAccess.",new Each(facilitiesAccess));
        mongoTemplate.updateFirst(query, update, User.class);
        return null;
    }

1 Comment

no, its still showing an error. not working suggest me any another

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.