PoM
PoM

Reputation: 161

Parse Cloud - Get user informations by objectId

I'm trying to get user lang from User class in Parse Cloud. lang is one of the columns in User class. I wanna get lang of the user. My entire Cloud Code is as following (it didn't work):

Parse.Cloud.beforeSave('Order', function(request, response) {

    var orderState = request.object.get('orderState');
    var subtitleMessage = '';

    var userLang = '';
    var currentUser = request.object.get('user');
    var userQuery = new Parse.Query(Parse.User);
    userQuery.equalTo('objectId', currentUser.id);
    .find()
    .then((result)=>{
        userLang = result.get('lang');
    })

    if (orderState === undefined || ['nonApproved', 'approved', 'delivered', 'canceled'].indexOf(orderState) < 0) {
        response.error("OrderState is null or not one the ['nonApproved', 'approved', 'delivered', 'canceled']!");
    } else {
        var query = new Parse.Query(Parse.Installation);
        query.include('user');
        query.equalTo('user', request.object.get('user'));

        Parse.Push.send(
            {
                where: query,
                data: {
                    title: "MyTitle",
                    alert: subtitleMessage
                }
            },
            {
                success: function() {
                },
                error: function(error) {
                    response.error(error)
                },
                useMasterKey: true
            }
        );
        response.success();
    }
});

Upvotes: 0

Views: 417

Answers (2)

JeremyPlease
JeremyPlease

Reputation: 666

The answer from Jake T. has some good points. Based on his answer and your comment on the question, you could try something like this:

Parse.Cloud.beforeSave('Order', function(request, response) {
  var currentUser = request.object.get('user');
  currentUser.fetch({useMasterKey: true}).then(function(user) {
    var userLang = user.get('lang');
    // send push notifications based on userLang here
    response.success();
  }).catch(function(error) {
    // handle any errors here
    console.error(error);
  });
});

Upvotes: 1

Jake T.
Jake T.

Reputation: 4378

Verify you actually have a User object shell from request.object.get("user"); And, if you do, you can just call currentUser.fetch() instead of performing a query, unless there are other objects you may need to include.

Since you used a query, the result is an array, even if there is only a single object returned (or none, it would be simply []). So, you're doing Array.get("lang"), which shouldn't do anything. Try if( results && results.length > 0 ) user = results[0];, then you should be able to access user.get("lang");

You should have ACL / CLP's set up for your User class. Ideally, these should not be accessible by people who are not the user or master. So, if that is set up properly, your solution may be passing {useMasterKey:true} as an option to the query / fetch.

Upvotes: 0

Related Questions