Search code examples
javascriptunderscore.jsparse-server

Underscores _.clone() does not work with Parse JS SDK compound queries


I'm having trouble getting this to work in Parse Server v2.3.7 (which includes Parse JS SDK v1.9.2) with sorting a compound query. I can use ascending/descending query methods in the original query, but when I clone it they no longer work. Any ideas why this isn't working or is there a better approach to cloning the query?

var firstQuery = new Parse.Query('Object');
firstQuery.equalTo('property', 1);
var secondQuery = new Parse.Query('Object');
secondQuery.equalTo('property', 2);

var query = Parse.Query.or(firstQuery, secondQuery);
query.descending('updatedAt');
// This works
var clonedQuery = _.clone(query);
clonedQuery.ascending('updatedAt');
// Throws error "clonedQuery.ascending is not a function"

Continuing this issue: How can I clone a Parse Query using the Javascript SDK on Parse Cloud Code?


Solution

  • Updated

    There is one thing Lodash.js does which Underscore.js doesn't. Lodash.js copy the prototype while Underscore.js sets prototype to undefined. To make it works with Underscore.js, you need to copy the prototype manually:

    var Parse = require('parse').Parse;
    var _ = require('underscore');
    
    var firstQuery = new Parse.Query('Object');
    firstQuery.equalTo('property', 1);
    var secondQuery = new Parse.Query('Object');
    secondQuery.equalTo('property', 2);
    
    var query = Parse.Query.or(firstQuery, secondQuery);
    query.descending('updatedAt');
    // This works
    var clonedQuery = _.clone(query);
    Object.setPrototypeOf(clonedQuery, Object.getPrototypeOf(query)); // This line is very important!
    clonedQuery.ascending('updatedAt');
    // This works too