Limit search to retrieve specific items based on pointer in JavaScript using Parse.com

BlogApp.Collections.Blogs = Parse.Collection.extend({
    model: BlogApp.Models.Blog,
    query: (new Parse.Query(BlogApp.Models.Blog)).equalTo("author", "xMQR0A1Us6").descending('createdAt').limit(9)
});

The code snippet above doesn't seem to be functioning as expected. While I can easily perform operations on columns that already exist within the class, such as .equalTo("productType", "SHIRT"), linking to the author field which resides in a separate User class seems challenging.

Is there a way to modify the query so that it only retrieves items where the "author" (a pointer) matches an objectId from the User class?

Model:

BlogApp.Models.Blog = Parse.Object.extend('MarketDesign', {

    update: function(form) {

        if ( !this.get('ACL') ) {
            var blogACL = new Parse.ACL(Parse.User.current());
            blogACL.setPublicReadAccess(true);
            this.setACL(blogACL);
        }

        BlogApp.category.id = form.category;

        this.set({
            'title': form.title,
            'url': form.title.toLowerCase()
            .replace(/[^\w ]+/g,'')
            .replace(/ +/g,'-'),
            'category': BlogApp.category,
            'comment': form.content,
            'author': this.get('author') || Parse.User.current(),
            'authorName': this.get('authorName') || Parse.User.current().get('username'),
            'time': this.get('time') || new Date().toDateString()
        }).save(null, {
            success: function(blog) {
                Parse.history.navigate('#/admin', { trigger: true });
                window.location.reload();
            },
            error: function(blog, error) {
                console.log(error);
            }
        });
    }

});

Answer №1

Understanding the difference between objectId, which is simply a string, and a pointer is crucial. When comparing a Pointer column in a query, it requires passing a parse object. For instance, when searching for Blogs where the author is the current user...

var user = Parse.User.current();   // no .id, that's important!
BlogApp.Collections.Blogs = Parse.Collection.extend({
    model: BlogApp.Models.Blog,
    query: (new Parse.Query(BlogApp.Models.Blog)).equalTo("author", user).descending('createdAt').limit(9)
});

If you only have the objectId, create an object using it like so:

var user = Parse.User.createWithoutData("xMQR0A1Us6"); 

However, I strongly advise against this approach. If you possess an object id, then you must have had the entire object to which it corresponds at some point. In general, avoid retaining object ids; instead, store the objects they relate to so you can access any part of them later on.

Answer №2

After conducting some research, I discovered that the .equalTo method cannot be used to query an element within the specified class. You can read more about this limitation here:

While this information didn't provide a solution to my specific issue, it may help others understand what I am trying to achieve:

BlogApp.Collections.UserDesigns = Parse.Collection.extend({
    model: BlogApp.Models.Blog,
    query: (new Parse.Query(BlogApp.Models.Blog)).matchesQuery("author", Parse.User.current().id).descending('createdAt').limit(3)
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error alert must be displayed directly beneath the specific box

When error messages occur in this code, they are displayed through an alert box. However, I would prefer to have the error message appear below the specific text box instead. This means that when I click on the submit button and a field is left empty, the ...

Inexplicably, HighCharts flips its axis when exporting data

I am facing an issue with the display of my Highchart in the web application. While it appears correctly in the browser, the exported chart flips the axis and shows a different image. Below are the options I have configured for my Highchart: var options = ...

Tips on transferring form data from client to server in meteor

In the process of developing my e-commerce application, I am facing a challenge with passing data from the client to the server. Specifically, I need to send information like the total cost of items in the cart and the list of items selected by users so ...

Issue with AngularJS: $compile function is not functioning as expected

In this particular code snippet, I am encountering an issue with the $compile function. What I am trying to accomplish is taking an item, adding it to the scope, and then compiling it to generate HTML. $http({ method: 'GET', ...

Is it time to release the BufferGeometry?

My scene objects are structured around a single root Object3D, with data loaded as a tree of Object3Ds branching from this root. Meshes are attached to the leaf Object3Ds using BufferGeometry/MeshPhongMaterial. To clear the existing tree structure, I use t ...

Having trouble sending an array's JSON data to a web service using Angular

I am working with a table where each cell in the rows contains form fields. The table also has two buttons: one button adds a new row to the table, and the other sends all the rows. Below is the code snippet for adding new blank rows: $scope.attributes = ...

Using AJAX to Interact with PHP

Currently, I am facing a problem with my PHP code where my For each loop is not properly waiting for the response of the AJAX call. I have attempted to incorporate Promise functions to solve this issue but unfortunately, it did not work out as expected. ...

Having trouble getting the "save adjustments" button to become enabled after using the jQuery datepicker

It's puzzling that my code doesn't respond to the selection of a date using the jQuery date picker to re-enable the "save changes" button. Interestingly, changing values in other input boxes seems to work perfectly fine. I'm struggling to gr ...

Utilize the lodash times method for indexing

I have a requirement to duplicate a component "n" number of times. I achieved this by utilizing the lodash method called "times". However, I encountered an issue with assigning an index as a key for the generated components. Below is the snippet of code t ...

Error encountered while using the Fetch API: SyntaxError - the JSON data contains an unexpected character at the beginning

I've been troubleshooting a contact form and there seems to be an error causing it to malfunction. It's strange because when I switch from Fetch to XMLHttpRequest, the code works fine. With Fetch, if I don't request a response, no errors ar ...

Angular Pagination: Present a collection of pages formatted to the size of A4 paper

Currently, I am working on implementing pagination using NgbdPaginationBasic in my app.module.ts file. import { NgbdPaginationBasic } from './pagination-basic'; My goal is to create a series of A4 size pages with a visible Header and Footer onl ...

How can we use JavaScript to add a class to the <html> element?

What is the method to apply a class to the root element <html> in JavaScript? ...

Using Mongoose and MongoDB to reference a different schema without using the default ObjectId reference

I have two different schemas in my current project. var carSchema = new mongoose.Schema({ id: { type: Number, unique: true, required: true }, make: { type: String, required: true }, model: { ...

Navigating to a different state key within a state object in React - a simple guide

Trying to dive into React, I encountered an issue. My goal is to create my own example from a tutorial. import React, { Component } from 'react'; class MyComponent extends Component { state = { persons: [], firstPersons: 5, variab ...

Modify Bootstrap Card Styling Using JavaScript

When the clock strikes certain evening hours on my website, the Bootstrap card's default light style no longer fits the dark theme. I've attempted to switch the card to a dark style by tying in some JavaScript code, but it's not quite doing ...

Is it possible to restrict the acceptance of certain variables from a CSV file in Django form fields, instead of accepting

In my Django model, I have two fields for latitude and longitude which are both declared as CharField. The model needs to accept multiple coordinates, so in the UI form, I enter these coordinates separated by commas. I then split this char input in a funct ...

Eliminate lower values in select 1 if the value selected in select 2 is higher

I am struggling with a particular piece of code and could really use some assistance. Within my project, I have two select boxes. The first box allows users to select the "from" year, while the second box is for selecting the "to" year. What I'm tryi ...

Bug in Async.js causes unexpected results in loop involving numbers

When attempting to reference a variable in a for loop using the Async Library for Node.js, it seems to not work as expected. Here is an example: var functionArray = [] , x; for(x = 0; x < 5; x++) { functionArray.push(function (callback) { conso ...

Changing the class of a div in JavaScript from one class to another

On my HTML page, I have a div with a CSS class assigned to it. The goal is to switch the current class for another when a button is clicked. It's crucial that not a single CSS property within the class is altered - the entire class must be replaced en ...

Developing a modular text input component with Material UI and react-hook-form for enhanced reusability

While I was in the process of creating a reusable text field component using Material UI and react-hook-form, I decided to refer to a couple of examples for guidance: Example 1 source: type FormProps<TFormValues> = { onSubmit: SubmitHandler& ...