diff --git a/_includes/js/analytics.md b/_includes/js/analytics.md index cf701ad0f..22ed97202 100644 --- a/_includes/js/analytics.md +++ b/_includes/js/analytics.md @@ -14,7 +14,7 @@ Without having to implement any client-side logic, you can view real-time graphs Say your app offers search functionality for apartment listings, and you want to track how often the feature is used, with some additional metadata. ```javascript -var dimensions = { +const dimensions = { // Define ranges to bucket data points into meaningful segments priceRange: '1000-1500', // Did the user filter the query? @@ -29,7 +29,7 @@ Parse.Analytics.track('search', dimensions); `Parse.Analytics` can even be used as a lightweight error tracker — simply invoke the following and you'll have access to an overview of the rate and frequency of errors, broken down by error code, in your application: ```javascript -var codeString = '' + error.code; +const codeString = '' + error.code; Parse.Analytics.track('error', { code: codeString }); ``` diff --git a/_includes/js/files.md b/_includes/js/files.md index 2f04665e5..90cf28500 100644 --- a/_includes/js/files.md +++ b/_includes/js/files.md @@ -7,21 +7,21 @@ Getting started with `Parse.File` is easy. There are a couple of ways to create a file. The first is with a base64-encoded String. ```javascript -var base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE="; -var file = new Parse.File("myfile.txt", { base64: base64 }); +const base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE="; +const file = new Parse.File("myfile.txt", { base64: base64 }); ``` Alternatively, you can create a file from an array of byte values: ```javascript -var bytes = [ 0xBE, 0xEF, 0xCA, 0xFE ]; -var file = new Parse.File("myfile.txt", bytes); +const bytes = [ 0xBE, 0xEF, 0xCA, 0xFE ]; +const file = new Parse.File("myfile.txt", bytes); ``` Parse will auto-detect the type of file you are uploading based on the file extension, but you can specify the `Content-Type` with a third parameter: ```javascript -var file = new Parse.File("myfile.zzz", fileData, "image/png"); +const file = new Parse.File("myfile.zzz", fileData, "image/png"); ``` ### Client Side @@ -34,12 +34,12 @@ In a browser, you'll want to use an html form with a file upload control. To do Then, in a click handler or other function, get a reference to that file: ```javascript -var fileUploadControl = $("#profilePhotoFileUpload")[0]; +const fileUploadControl = $("#profilePhotoFileUpload")[0]; if (fileUploadControl.files.length > 0) { - var file = fileUploadControl.files[0]; - var name = "photo.jpg"; + const file = fileUploadControl.files[0]; + const name = "photo.jpg"; - var parseFile = new Parse.File(name, file); + const parseFile = new Parse.File(name, file); } ``` @@ -88,7 +88,7 @@ request(options) Finally, after the save completes, you can associate a `Parse.File` with a `Parse.Object` just like any other piece of data: ```javascript -var jobApplication = new Parse.Object("JobApplication"); +const jobApplication = new Parse.Object("JobApplication"); jobApplication.set("applicantName", "Joe Smith"); jobApplication.set("applicantResumeFile", parseFile); jobApplication.save(); @@ -99,7 +99,7 @@ jobApplication.save(); How to best retrieve the file contents back depends on the context of your application. Because of cross-domain request issues, it's best if you can make the browser do the work for you. Typically, that means rendering the file's URL into the DOM. Here we render an uploaded profile photo on a page with jQuery: ```javascript -var profilePhoto = profile.get("photoFile"); +const profilePhoto = profile.get("photoFile"); $("profileImg")[0].src = profilePhoto.url(); ``` diff --git a/_includes/js/geopoints.md b/_includes/js/geopoints.md index c68439748..9accb70cb 100644 --- a/_includes/js/geopoints.md +++ b/_includes/js/geopoints.md @@ -7,7 +7,7 @@ Parse allows you to associate real-world latitude and longitude coordinates with To associate a point with an object you first need to create a `Parse.GeoPoint`. For example, to create a point with latitude of 40.0 degrees and -30.0 degrees longitude: ```javascript -var point = new Parse.GeoPoint({latitude: 40.0, longitude: -30.0}); +const point = new Parse.GeoPoint({latitude: 40.0, longitude: -30.0}); ``` This point is then stored in the object as a regular field. @@ -67,10 +67,10 @@ const pizzaPlacesInSF = query.find(); It's also possible to query for the set of objects that are contained within a particular area. To find the objects in a rectangular bounding box, add the `withinGeoBox` restriction to your `Parse.Query`. ```javascript -var southwestOfSF = new Parse.GeoPoint(37.708813, -122.526398); -var northeastOfSF = new Parse.GeoPoint(37.822802, -122.373962); +const southwestOfSF = new Parse.GeoPoint(37.708813, -122.526398); +const northeastOfSF = new Parse.GeoPoint(37.822802, -122.373962); -var query = new Parse.Query(PizzaPlaceObject); +const query = new Parse.Query(PizzaPlaceObject); query.withinGeoBox("location", southwestOfSF, northeastOfSF); const pizzaPlacesInSF = await query.find(); ``` diff --git a/_includes/js/getting-started.md b/_includes/js/getting-started.md index 730cd5d1a..f99c92319 100644 --- a/_includes/js/getting-started.md +++ b/_includes/js/getting-started.md @@ -8,14 +8,14 @@ The JavaScript ecosystem is wide and incorporates a large number of platforms an To use the npm modules for a browser based application, include it as you normally would: ```js -var Parse = require('parse'); +const Parse = require('parse'); ``` For server-side applications or Node.js command line tools, include `'parse/node'`: ```js // In a node.js environment -var Parse = require('parse/node'); +const Parse = require('parse/node'); // ES6 Minimized import Parse from 'parse/dist/parse.min.js'; ``` @@ -23,7 +23,7 @@ import Parse from 'parse/dist/parse.min.js'; For React Native applications, include `'parse/react-native.js'`: ```js // In a React Native application -var Parse = require('parse/react-native.js'); +const Parse = require('parse/react-native.js'); ``` Additionally on React-Native / Expo environments, make sure to add the piece of code below : diff --git a/_includes/js/objects.md b/_includes/js/objects.md index c8b9df703..c3fce7580 100644 --- a/_includes/js/objects.md +++ b/_includes/js/objects.md @@ -18,13 +18,13 @@ To create a new subclass, use the `Parse.Object.extend` method. Any `Parse.Quer ```javascript // Simple syntax to create a new subclass of Parse.Object. -var GameScore = Parse.Object.extend("GameScore"); +const GameScore = Parse.Object.extend("GameScore"); // Create a new instance of that class. -var gameScore = new GameScore(); +const gameScore = new GameScore(); // Alternatively, you can use the typical Backbone syntax. -var Achievement = Parse.Object.extend({ +const Achievement = Parse.Object.extend({ className: "Achievement" }); ``` @@ -34,7 +34,7 @@ You can add additional methods and properties to your subclasses of `Parse.Objec ```javascript // A complex subclass of Parse.Object -var Monster = Parse.Object.extend("Monster", { +const Monster = Parse.Object.extend("Monster", { // Instance methods hasSuperHumanStrength: function () { return this.get("strength") > 18; @@ -46,13 +46,13 @@ var Monster = Parse.Object.extend("Monster", { }, { // Class methods spawn: function(strength) { - var monster = new Monster(); + const monster = new Monster(); monster.set("strength", strength); return monster; } }); -var monster = Monster.spawn(200); +const monster = Monster.spawn(200); alert(monster.get('strength')); // Displays 200. alert(monster.sound); // Displays Rawr. ``` @@ -75,7 +75,7 @@ class Monster extends Parse.Object { } static spawn(strength) { - var monster = new Monster(); + const monster = new Monster(); monster.set('strength', strength); return monster; } @@ -156,8 +156,8 @@ There are also a few fields you don't need to specify that are provided as a con If you prefer, you can set attributes directly in your call to `save` instead. ```javascript -var GameScore = Parse.Object.extend("GameScore"); -var gameScore = new GameScore(); +const GameScore = Parse.Object.extend("GameScore"); +const gameScore = new GameScore(); gameScore.save({ score: 1337, @@ -176,13 +176,13 @@ gameScore.save({ You may add a `Parse.Object` as the value of a property in another `Parse.Object`. By default, when you call `save()` on the parent object, all nested objects will be created and/or saved as well in a batch operation. This feature makes it really easy to manage relational data as you don't have to take care of creating the objects in any specific order. ```javascript -var Child = Parse.Object.extend("Child"); -var child = new Child(); +const Child = Parse.Object.extend("Child"); +const child = new Child(); -var Parent = Parse.Object.extend("Parent"); -var parent = new Parent(); +const Parent = Parse.Object.extend("Parent"); +const parent = new Parent(); -parent.save({child: child}); +parent.save({ child: child }); // Automatically the object Child is created on the server // just before saving the Parent ``` @@ -190,8 +190,8 @@ parent.save({child: child}); In some scenarios, you may want to prevent this default chain save. For example, when saving a team member's profile that points to an account owned by another user to which you don't have write access. In this case, setting the option `cascadeSave` to `false` may be useful: ```javascript -var TeamMember = Parse.Object.extend("TeamMember"); -var teamMember = new TeamMember(); +const TeamMember = Parse.Object.extend("TeamMember"); +const teamMember = new TeamMember(); teamMember.set('ownerAccount', ownerAccount); // Suppose `ownerAccount` has been created earlier. teamMember.save(null, { cascadeSave: false }); @@ -206,11 +206,11 @@ teamMember.save(null, { cascadeSave: false }); You may pass a `context` dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers for that `Parse.Object`. This is useful if you want to condition certain operations in Cloud Code triggers on ephemeral information that should not be saved with the `Parse.Object` in the database. The context is ephemeral in the sense that it vanishes after the Cloud Code triggers for that particular `Parse.Object` have executed. For example: ```javascript -var TeamMember = Parse.Object.extend("TeamMember"); -var teamMember = new TeamMember(); +const TeamMember = Parse.Object.extend("TeamMember"); +const teamMember = new TeamMember(); teamMember.set("team", "A"); -var context = { notifyTeam: false }; +const context = { notifyTeam: false }; await teamMember.save(null, { context: context }); ``` @@ -218,10 +218,10 @@ The context is then accessible in Cloud Code: ```javascript Parse.Cloud.afterSave("TeamMember", async (req) => { - var notifyTeam = req.context.notifyTeam; - if (notifyTeam) { - // Notify team about new member. - } + const notifyTeam = req.context.notifyTeam; + if (notifyTeam) { + // Notify team about new member. + } }); ``` @@ -230,8 +230,8 @@ Parse.Cloud.afterSave("TeamMember", async (req) => { Saving data to the cloud is fun, but it's even more fun to get that data out again. If the `Parse.Object` has been uploaded to the server, you can use the `objectId` to get it using a `Parse.Query`: ```javascript -var GameScore = Parse.Object.extend("GameScore"); -var query = new Parse.Query(GameScore); +const GameScore = Parse.Object.extend("GameScore"); +const query = new Parse.Query(GameScore); query.get("xWMyZ4YEGZ") .then((gameScore) => { // The object was retrieved successfully. @@ -244,9 +244,9 @@ query.get("xWMyZ4YEGZ") To get the values out of the `Parse.Object`, use the `get` method. ```javascript -var score = gameScore.get("score"); -var playerName = gameScore.get("playerName"); -var cheatMode = gameScore.get("cheatMode"); +const score = gameScore.get("score"); +const playerName = gameScore.get("playerName"); +const cheatMode = gameScore.get("cheatMode"); ``` Alternatively, the `attributes` property of the `Parse.Object` can be treated as a Javascript object, and even destructured. @@ -258,10 +258,10 @@ const { score, playerName, cheatMode } = result.attributes; The four special reserved values are provided as properties and cannot be retrieved using the 'get' method nor modified with the 'set' method: ```javascript -var objectId = gameScore.id; -var updatedAt = gameScore.updatedAt; -var createdAt = gameScore.createdAt; -var acl = gameScore.getACL(); +const objectId = gameScore.id; +const updatedAt = gameScore.updatedAt; +const createdAt = gameScore.createdAt; +const acl = gameScore.getACL(); ``` If you need to refresh an object you already have with the latest data that @@ -290,8 +290,8 @@ Updating an object is simple. Just set some new data on it and call the save met ```javascript // Create the object. -var GameScore = Parse.Object.extend("GameScore"); -var gameScore = new GameScore(); +const GameScore = Parse.Object.extend("GameScore"); +const gameScore = new GameScore(); gameScore.set("score", 1337); gameScore.set("playerName", "Sean Plott"); @@ -378,16 +378,16 @@ To create a new `Post` with a single `Comment`, you could write: ```javascript // Declare the types. -var Post = Parse.Object.extend("Post"); -var Comment = Parse.Object.extend("Comment"); +const Post = Parse.Object.extend("Post"); +const Comment = Parse.Object.extend("Comment"); // Create the post -var myPost = new Post(); +const myPost = new Post(); myPost.set("title", "I'm Hungry"); myPost.set("content", "Where should we go for lunch?"); // Create the comment -var myComment = new Comment(); +const myComment = new Comment(); myComment.set("content", "Let's do Sushirrito."); // Add the post as a value in the comment @@ -400,7 +400,7 @@ myComment.save(); Internally, the Parse framework will store the referred-to object in just one place, to maintain consistency. You can also link objects using just their `objectId`s like so: ```javascript -var post = new Post(); +const post = new Post(); post.id = "1zEcyElZ80"; myComment.set("parent", post); @@ -419,8 +419,8 @@ const title = post.get("title"); Many-to-many relationships are modeled using `Parse.Relation`. This works similar to storing an array of `Parse.Object`s in a key, except that you don't need to fetch all of the objects in a relation at once. In addition, this allows `Parse.Relation` to scale to many more objects than the array of `Parse.Object` approach. For example, a `User` may have many `Posts` that she might like. In this case, you can store the set of `Posts` that a `User` likes using `relation`. In order to add a `Post` to the "likes" list of the `User`, you can do: ```javascript -var user = Parse.User.current(); -var relation = user.relation("likes"); +const user = Parse.User.current(); +const relation = user.relation("likes"); relation.add(post); user.save(); ``` @@ -460,7 +460,7 @@ relation.query().find({ If you want only a subset of the Posts, you can add extra constraints to the `Parse.Query` returned by query like this: ```javascript -var query = relation.query(); +const query = relation.query(); query.equalTo("title", "I'm Hungry"); query.find({ success:function(list) { @@ -489,16 +489,16 @@ So far we've used values with type `String`, `Number`, and `Parse.Object`. Parse Some examples: ```javascript -var number = 42; -var bool = false; -var string = "the number is " + number; -var date = new Date(); -var array = [string, number]; -var object = { number: number, string: string }; -var pointer = MyClassName.createWithoutData(objectId); +const number = 42; +const bool = false; +const string = "the number is " + number; +const date = new Date(); +const array = [string, number]; +const object = { number: number, string: string }; +const pointer = MyClassName.createWithoutData(objectId); -var BigObject = Parse.Object.extend("BigObject"); -var bigObject = new BigObject(); +const BigObject = Parse.Object.extend("BigObject"); +const bigObject = new BigObject(); bigObject.set("myNumber", number); bigObject.set("myBool", bool); bigObject.set("myString", string); diff --git a/_includes/js/promises.md b/_includes/js/promises.md index 490e5e8af..d106f6805 100644 --- a/_includes/js/promises.md +++ b/_includes/js/promises.md @@ -79,7 +79,7 @@ obj.save().then(function(obj) { Promises are a little bit magical, in that they let you chain them without nesting. If a callback for a promise returns a new promise, then the first one will not be resolved until the second one is. This lets you perform multiple actions without incurring the pyramid code you would get with callbacks. ```javascript -var query = new Parse.Query("Student"); +const query = new Parse.Query("Student"); query.descending("gpa"); query.find().then(function(students) { students[0].set("valedictorian", true); @@ -144,7 +144,7 @@ Parse.User.logIn("user", "pass").then(function(user) { Generally, developers consider a failing promise to be the asynchronous equivalent to throwing an exception. In fact, if a callback passed to `then` throws an error, the promise returned will fail with that error. If any Promise in a chain returns an error, all of the success callbacks after it will be skipped until an error callback is encountered. The error callback can transform the error, or it can handle it by returning a new Promise that isn't rejected. You can think of rejected promises kind of like throwing an exception. An error callback is like a catch block that can handle the error or rethrow it. ```javascript -var query = new Parse.Query("Student"); +const query = new Parse.Query("Student"); query.descending("gpa"); query.find().then(function(students) { students[0].set("valedictorian", true); @@ -224,7 +224,7 @@ query.find().then(function(results) { With these tools, it's easy to make your own asynchronous functions that return promises. For example, you can make a promisified version of `setTimeout`. ```javascript -var delay = function(millis) { +const delay = function(millis) { return new Promise((resolve) => { setTimeout(resolve, millis); }); diff --git a/_includes/js/push-notifications.md b/_includes/js/push-notifications.md index d18745236..e9a9f5e41 100644 --- a/_includes/js/push-notifications.md +++ b/_includes/js/push-notifications.md @@ -91,7 +91,7 @@ The JavaScript SDK does not currently support modifying `Installation` objects. Once you have your data stored on your `Installation` objects, you can use a query to target a subset of these devices. `Parse.Installation` queries work just like any other [Parse query](#queries). ```javascript -var query = new Parse.Query(Parse.Installation); +const query = new Parse.Query(Parse.Installation); query.equalTo('injuryReports', true); Parse.Push.send({ @@ -110,7 +110,7 @@ Parse.Push.send({ We can even use channels with our query. To send a push to all subscribers of the "Giants" channel but filtered by those who want score update, we can do the following: ```javascript -var query = new Parse.Query(Parse.Installation); +const query = new Parse.Query(Parse.Installation); query.equalTo('channels', 'Giants'); // Set our channel query.equalTo('scores', true); @@ -131,11 +131,11 @@ If we store relationships to other objects in our `Installation` class, we can a ```javascript // Find users near a given location -var userQuery = new Parse.Query(Parse.User); +const userQuery = new Parse.Query(Parse.User); userQuery.withinMiles("location", stadiumLocation, 1.0); // Find devices associated with these users -var pushQuery = new Parse.Query(Parse.Installation); +const pushQuery = new Parse.Query(Parse.Installation); pushQuery.matchesQuery('user', userQuery); // Send push notification to query @@ -192,7 +192,7 @@ Parse.Push.send({ It is also possible to specify your own data in this dictionary. As explained in the Receiving Notifications section for [iOS]({{ site.baseUrl }}/ios/guide/#receiving-pushes) and [Android]({{ site.baseUrl }}/android/guide/#receiving-pushes), iOS will give you access to this data only when the user opens your app via the notification and Android will provide you this data in the `Intent` if one is specified. ```javascript -var query = new Parse.Query(Parse.Installation); +const query = new Parse.Query(Parse.Installation); query.equalTo('channels', 'Indians'); query.equalTo('injuryReports', true); @@ -219,7 +219,7 @@ When a user's device is turned off or not connected to the internet, push notifi There are two parameters provided by Parse to allow setting an expiration date for your notification. The first is `expiration_time` which takes a `Date` specifying when Parse should stop trying to send the notification. To expire the notification exactly 1 week from now, you can use the following: ```javascript -var oneWeekAway = new Date(...); +const oneWeekAway = new Date(...); Parse.Push.send({ where: everyoneQuery, @@ -238,8 +238,8 @@ Parse.Push.send({ Alternatively, you can use the `expiration_interval` parameter to specify a duration of time before your notification expires. This value is relative to the `push_time` parameter used to [schedule notifications](#scheduling-pushes). This means that a push notification scheduled to be sent out in 1 day and an expiration interval of 6 days can be received up to a week from now. ```javascript -var oneDayAway = new Date(...); -var sixDaysAwayEpoch = (new Date(...)).getTime(); +const oneDayAway = new Date(...); +const sixDaysAwayEpoch = (new Date(...)).getTime(); Parse.Push.send({ push_time: oneDayAway, @@ -263,7 +263,7 @@ The following examples would send a different notification to Android and iOS us ```javascript // Notification for Android users -var queryAndroid = new Parse.Query(Parse.Installation); +const queryAndroid = new Parse.Query(Parse.Installation); queryAndroid.equalTo('deviceType', 'android'); Parse.Push.send({ @@ -274,7 +274,7 @@ Parse.Push.send({ }); // Notification for iOS users -var queryIOS = new Parse.Query(Parse.Installation); +const queryIOS = new Parse.Query(Parse.Installation); queryIOS.equalTo('deviceType', 'ios'); Parse.Push.send({ @@ -285,7 +285,7 @@ Parse.Push.send({ }); // Notification for Windows 8 users -var queryWindows = new Parse.Query(Parse.Installation); +const queryWindows = new Parse.Query(Parse.Installation); queryWindows.equalTo('deviceType', 'winrt'); Parse.Push.send({ @@ -296,7 +296,7 @@ Parse.Push.send({ }); // Notification for Windows Phone 8 users -var queryWindowsPhone = new Parse.Query(Parse.Installation); +const queryWindowsPhone = new Parse.Query(Parse.Installation); queryWindowsPhone.equalTo('deviceType', 'winphone'); Parse.Push.send({ @@ -312,9 +312,9 @@ Parse.Push.send({ You can schedule a push in advance by specifying a `push_time`. For example, if a user schedules a game reminder for a game tomorrow at noon UTC, you can schedule the push notification by sending: ```javascript -var tomorrowDate = new Date(...); +const tomorrowDate = new Date(...); -var query = new Parse.Query(Parse.Installation); +const query = new Parse.Query(Parse.Installation); query.equalTo('user', user); Parse.Push.send({ diff --git a/_includes/js/queries.md b/_includes/js/queries.md index 56ea5c325..0067adc3c 100644 --- a/_includes/js/queries.md +++ b/_includes/js/queries.md @@ -16,7 +16,7 @@ const results = await query.find(); alert("Successfully retrieved " + results.length + " scores."); // Do something with the returned Parse.Object values for (let i = 0; i < results.length; i++) { - var object = results[i]; + const object = results[i]; alert(object.id + ' - ' + object.get('playerName')); } ``` @@ -146,7 +146,7 @@ const results = await userQuery.find(); Conversely, to get objects where a key does not match the value of a key in a set of objects resulting from another query, use `doesNotMatchKeyInQuery`. For example, to find users whose hometown teams have losing records: ```javascript -var losingUserQuery = new Parse.Query(Parse.User); +const losingUserQuery = new Parse.Query(Parse.User); losingUserQuery.doesNotMatchKeyInQuery("hometown", "city", teamQuery); // results has the list of users with a hometown team with a losing record const results = await losingUserQuery.find(); @@ -168,8 +168,8 @@ groupsWithRoleX.find().then(function(results) { You can restrict the fields returned by calling `select` with a list of keys. To retrieve documents that contain only the `score` and `playerName` fields (and also special built-in fields such as `objectId`, `createdAt`, and `updatedAt`): ```javascript -var GameScore = Parse.Object.extend("GameScore"); -var query = new Parse.Query(GameScore); +const GameScore = Parse.Object.extend("GameScore"); +const query = new Parse.Query(GameScore); query.select("score", "playerName"); query.find().then(function(results) { // each of results will only have the selected fields available. @@ -179,8 +179,8 @@ query.find().then(function(results) { Similarly, use `exclude` to remove undesired fields while retrieving the rest: ```javascript -var GameScore = Parse.Object.extend("GameScore"); -var query = new Parse.Query(GameScore); +const GameScore = Parse.Object.extend("GameScore"); +const query = new Parse.Query(GameScore); query.exclude("playerName"); query.find().then(function(results) { // Now each result will have all fields except `playerName` @@ -221,7 +221,7 @@ Use `startsWith` to restrict to string values that start with a particular strin ```javascript // Finds barbecue sauces that start with "Big Daddy's". -var query = new Parse.Query(BarbecueSauce); +const query = new Parse.Query(BarbecueSauce); query.startsWith("name", "Big Daddy's"); ``` @@ -238,7 +238,7 @@ You can use `fullText` for efficient search capabilities. Text indexes are autom * Parse Server 2.5.0+ ```javascript -var query = new Parse.Query(BarbecueSauce); +const query = new Parse.Query(BarbecueSauce); query.fullText('name', 'bbq'); ``` @@ -246,7 +246,7 @@ The above example will match any `BarbecueSauce` objects where the value in the ```javascript // You can sort by weight / rank. ascending() and select() -var query = new Parse.Query(BarbecueSauce); +const query = new Parse.Query(BarbecueSauce); query.fullText('name', 'bbq'); query.ascending('$score'); query.select('$score'); @@ -268,7 +268,7 @@ There are several ways to issue queries for relational data. If you want to retr ```javascript // Assume Parse.Object myPost was previously created. -var query = new Parse.Query(Comment); +const query = new Parse.Query(Comment); query.equalTo("post", myPost); // comments now contains the comments for myPost const comments = await query.find(); @@ -277,11 +277,11 @@ const comments = await query.find(); If you want to retrieve objects where a field contains a `Parse.Object` that matches a different query, you can use `matchesQuery`. In order to find comments for posts containing images, you can do: ```javascript -var Post = Parse.Object.extend("Post"); -var Comment = Parse.Object.extend("Comment"); -var innerQuery = new Parse.Query(Post); +const Post = Parse.Object.extend("Post"); +const Comment = Parse.Object.extend("Comment"); +const innerQuery = new Parse.Query(Post); innerQuery.exists("image"); -var query = new Parse.Query(Comment); +const query = new Parse.Query(Comment); query.matchesQuery("post", innerQuery); // comments now contains the comments for posts with images. const comments = await query.find(); @@ -290,11 +290,11 @@ const comments = await query.find(); If you want to retrieve objects where a field contains a `Parse.Object` that does not match a different query, you can use `doesNotMatchQuery`. In order to find comments for posts without images, you can do: ```javascript -var Post = Parse.Object.extend("Post"); -var Comment = Parse.Object.extend("Comment"); -var innerQuery = new Parse.Query(Post); +const Post = Parse.Object.extend("Post"); +const Comment = Parse.Object.extend("Comment"); +const innerQuery = new Parse.Query(Post); innerQuery.exists("image"); -var query = new Parse.Query(Comment); +const query = new Parse.Query(Comment); query.doesNotMatchQuery("post", innerQuery); // comments now contains the comments for posts without images. const comments = await query.find(); @@ -303,7 +303,7 @@ const comments = await query.find(); You can also do relational queries by `objectId`: ```javascript -var post = new Post(); +const post = new Post(); post.id = "1zEcyElZ80"; query.equalTo("post", post); ``` @@ -311,7 +311,7 @@ query.equalTo("post", post); In some situations, you want to return multiple types of related objects in one query. You can do this with the `include` method. For example, let's say you are retrieving the last ten comments, and you want to retrieve their related posts at the same time: ```javascript -var query = new Parse.Query(Comment); +const query = new Parse.Query(Comment); // Retrieve the most recent ones query.descending("createdAt"); @@ -325,9 +325,9 @@ query.include("post"); // Comments now contains the last ten comments, and the "post" field const comments = await query.find(); // has been populated. For example: -for (var i = 0; i < comments.length; i++) { +for (let i = 0; i < comments.length; i++) { // This does not require a network access. - var post = comments[i].get("post"); + const post = comments[i].get("post"); } ``` @@ -346,8 +346,8 @@ Note: In the old Parse hosted backend, count queries were rate limited to a maxi If you just need to count how many objects match a query, but you do not need to retrieve all the objects that match, you can use `count` instead of `find`. For example, to count how many games have been played by a particular player: ```javascript -var GameScore = Parse.Object.extend("GameScore"); -var query = new Parse.Query(GameScore); +const GameScore = Parse.Object.extend("GameScore"); +const query = new Parse.Query(GameScore); query.equalTo("playerName", "Sean Plott"); const count = await query.count(); alert("Sean has played " + count + " games"); @@ -366,13 +366,13 @@ Note that we do not support GeoPoint or non-filtering constraints (e.g. `near`, If you want to find objects that match one of several queries, you can use `Parse.Query.or` method to construct a query that is an OR of the queries passed in. For instance if you want to find players who either have a lot of wins or a few wins, you can do: ```javascript -var lotsOfWins = new Parse.Query("Player"); +const lotsOfWins = new Parse.Query("Player"); lotsOfWins.greaterThan("wins", 150); -var fewWins = new Parse.Query("Player"); +const fewWins = new Parse.Query("Player"); fewWins.lessThan("wins", 5); -var mainQuery = Parse.Query.or(lotsOfWins, fewWins); +const mainQuery = Parse.Query.or(lotsOfWins, fewWins); mainQuery.find() .then(function(results) { // results contains a list of players that either have won a lot of games or won only a few games. @@ -388,7 +388,7 @@ mainQuery.find() If you want to find objects that match all conditions, you normally would use just one query. You can add additional constraints to the newly created `Parse.Query` that act as an 'and' operator. ```javascript -var query = new Parse.Query("User"); +const query = new Parse.Query("User"); query.greaterThan("age", 18); query.greaterThan("friends", 0); query.find() @@ -403,19 +403,19 @@ query.find() Sometimes the world is more complex than this simple example and you may need a compound query of sub queries. You can use `Parse.Query.and` method to construct a query that is an AND of the queries passed in. For instance if you want to find users in the age of 16 or 18 who have either no friends or at least 2 friends, you can do: ```javascript -var age16Query = new Parse.Query("User"); +const age16Query = new Parse.Query("User"); age16Query.equalTo("age", 16); -var age18Query = new Parse.Query("User"); +const age18Query = new Parse.Query("User"); age18Query.equalTo("age", 18); -var friends0Query = new Parse.Query("User"); +const friends0Query = new Parse.Query("User"); friends0Query.equalTo("friends", 0); -var friends2Query = new Parse.Query("User"); +const friends2Query = new Parse.Query("User"); friends2Query.greaterThan("friends", 2); -var mainQuery = Parse.Query.and( +const mainQuery = Parse.Query.and( Parse.Query.or(age16Query, age18Query), Parse.Query.or(friends0Query, friends2Query) ); @@ -443,11 +443,11 @@ You can create a pipeline using an Array or an Object. The following example is a pipeline similar to `distinct` grouping by name field. ```javascript -var pipelineObject = { +const pipelineObject = { group: { objectId: '$name' } }; -var pipelineArray = [ +const pipelineArray = [ { group: { objectId: '$name' } } ]; ``` @@ -462,10 +462,10 @@ You can group by a field. ```javascript // score is the field. $ before score lets the database know this is a field -var pipeline = [ +const pipeline = [ { group: { objectId: '$score' } } ]; -var query = new Parse.Query("User"); +const query = new Parse.Query("User"); query.aggregate(pipeline) .then(function(results) { // results contains unique score values @@ -479,10 +479,10 @@ You can apply collective calculations like $sum, $avg, $max, $min. ```javascript // total will be a newly created field to hold the sum of score field -var pipeline = [ +const pipeline = [ { group: { objectId: null, total: { $sum: '$score' } } } ]; -var query = new Parse.Query("User"); +const query = new Parse.Query("User"); query.aggregate(pipeline) .then(function(results) { // results contains sum of score field and stores it in results[0].total @@ -495,10 +495,10 @@ query.aggregate(pipeline) Project pipeline is similar to `keys` or `select`, add or remove existing fields. ```javascript -var pipeline = [ +const pipeline = [ { project: { name: 1 } } ]; -var query = new Parse.Query("User"); +const query = new Parse.Query("User"); query.aggregate(pipeline) .then(function(results) { // results contains only name field @@ -511,10 +511,10 @@ query.aggregate(pipeline) Match pipeline is similar to `equalTo`. ```javascript -var pipeline = [ +const pipeline = [ { match: { name: 'BBQ' } } ]; -var query = new Parse.Query("User"); +const query = new Parse.Query("User"); query.aggregate(pipeline) .then(function(results) { // results contains name that matches 'BBQ' @@ -527,10 +527,10 @@ query.aggregate(pipeline) You can match by comparison. ```javascript -var pipeline = [ +const pipeline = [ { match: { score: { $gt: 15 } } } ]; -var query = new Parse.Query("User"); +const query = new Parse.Query("User"); query.aggregate(pipeline) .then(function(results) { // results contains score greater than 15 @@ -548,7 +548,7 @@ Queries can be made using distinct, allowing you find unique values for a specif * `MasterKey` is required. ```javascript -var query = new Parse.Query("User"); +const query = new Parse.Query("User"); query.distinct("age") .then(function(results) { // results contains unique age @@ -561,7 +561,7 @@ query.distinct("age") You can also restrict results by using `equalTo`. ```javascript -var query = new Parse.Query("User"); +const query = new Parse.Query("User"); query.equalTo("name", "foo"); query.distinct("age") .then(function(results) { diff --git a/_includes/js/roles.md b/_includes/js/roles.md index a96e0c36e..e5c4e065c 100644 --- a/_includes/js/roles.md +++ b/_includes/js/roles.md @@ -22,16 +22,16 @@ To create a new `Parse.Role`, you would write: ```javascript // By specifying no write privileges for the ACL, we can ensure the role cannot be altered. -var roleACL = new Parse.ACL(); +const roleACL = new Parse.ACL(); roleACL.setPublicReadAccess(true); -var role = new Parse.Role("Administrator", roleACL); +const role = new Parse.Role("Administrator", roleACL); role.save(); ``` You can add users and roles that should inherit your new role's permissions through the "users" and "roles" relations on `Parse.Role`: ```javascript -var role = new Parse.Role(roleName, roleACL); +const role = new Parse.Role(roleName, roleACL); role.getUsers().add(usersToAddToRole); role.getRoles().add(rolesToAddToRole); role.save(); @@ -46,9 +46,9 @@ Now that you have created a set of roles for use in your application, you can us Giving a role read or write permission to an object is straightforward. You can either use the `Parse.Role`: ```javascript -var moderators = /* Query for some Parse.Role */; -var wallPost = new Parse.Object("WallPost"); -var postACL = new Parse.ACL(); +const moderators = /* Query for some Parse.Role */; +const wallPost = new Parse.Object("WallPost"); +const postACL = new Parse.ACL(); postACL.setRoleWriteAccess(moderators, true); wallPost.setACL(postACL); wallPost.save(); @@ -57,8 +57,8 @@ wallPost.save(); You can avoid querying for a role by specifying its name for the ACL: ```javascript -var wallPost = new Parse.Object("WallPost"); -var postACL = new Parse.ACL(); +const wallPost = new Parse.Object("WallPost"); +const postACL = new Parse.ACL(); postACL.setRoleWriteAccess("Moderators", true); wallPost.setACL(postACL); wallPost.save(); @@ -71,8 +71,8 @@ As described above, one role can contain another, establishing a parent-child re These types of relationships are commonly found in applications with user-managed content, such as forums. Some small subset of users are "Administrators", with the highest level of access to tweaking the application's settings, creating new forums, setting global messages, and so on. Another set of users are "Moderators", who are responsible for ensuring that the content created by users remains appropriate. Any user with Administrator privileges should also be granted the permissions of any Moderator. To establish this relationship, you would make your "Administrators" role a child role of "Moderators", like this: ```javascript -var administrators = /* Your "Administrators" role */; -var moderators = /* Your "Moderators" role */; +const administrators = /* Your "Administrators" role */; +const moderators = /* Your "Moderators" role */; moderators.getRoles().add(administrators); moderators.save(); ``` diff --git a/_includes/js/users.md b/_includes/js/users.md index a306ac1af..b2ee7efe9 100644 --- a/_includes/js/users.md +++ b/_includes/js/users.md @@ -21,7 +21,7 @@ We'll go through each of these in detail as we run through the various use cases The first thing your app will do is probably ask the user to sign up. The following code illustrates a typical sign up: ```javascript -var user = new Parse.User(); +const user = new Parse.User(); user.set("username", "my name"); user.set("password", "my pass"); user.set("email", "email@example.com"); @@ -82,7 +82,7 @@ Please note that this functionality is disabled by default on Node.js environmen Whenever you use any signup or login methods, the user is cached in localStorage, or in any storage you configured via the `Parse.setAsyncStorage` method. You can treat this cache as a session, and automatically assume the user is logged in: ```javascript -var currentUser = Parse.User.current(); +const currentUser = Parse.User.current(); if (currentUser) { // do stuff with the user } else { @@ -102,7 +102,7 @@ You can clear the current user by logging them out: ```javascript Parse.User.logOut().then(() => { - var currentUser = Parse.User.current(); // this will now be null + const currentUser = Parse.User.current(); // this will now be null }); ``` @@ -168,8 +168,8 @@ The same security model that applies to the `Parse.User` can be applied to other The simplest way to use a `Parse.ACL` is to specify that an object may only be read or written by a single user. This is done by initializing a Parse.ACL with a `Parse.User`: `new Parse.ACL(user)` generates a `Parse.ACL` that limits access to that user. An object's ACL is updated when the object is saved, like any other property. Thus, to create a private note that can only be accessed by the current user: ```javascript -var Note = Parse.Object.extend("Note"); -var privateNote = new Note(); +const Note = Parse.Object.extend("Note"); +const privateNote = new Note(); privateNote.set("content", "This note is private!"); privateNote.setACL(new Parse.ACL(Parse.User.current())); privateNote.save(); @@ -180,12 +180,12 @@ This note will then only be accessible to the current user, although it will be Permissions can also be granted on a per-user basis. You can add permissions individually to a `Parse.ACL` using `setReadAccess` and `setWriteAccess`. For example, let's say you have a message that will be sent to a group of several users, where each of them have the rights to read and delete that message: ```javascript -var Message = Parse.Object.extend("Message"); -var groupMessage = new Message(); -var groupACL = new Parse.ACL(); +const Message = Parse.Object.extend("Message"); +const groupMessage = new Message(); +const groupACL = new Parse.ACL(); // userList is an array with the users we are sending this message to. -for (var i = 0; i < userList.length; i++) { +for (let i = 0; i < userList.length; i++) { groupACL.setReadAccess(userList[i], true); groupACL.setWriteAccess(userList[i], true); } @@ -197,8 +197,8 @@ groupMessage.save(); You can also grant permissions to all users at once using `setPublicReadAccess` and `setPublicWriteAccess`. This allows patterns like posting comments on a message board. For example, to create a post that can only be edited by its author, but can be read by anyone: ```javascript -var publicPost = new Post(); -var postACL = new Parse.ACL(Parse.User.current()); +const publicPost = new Post(); +const postACL = new Parse.ACL(Parse.User.current()); postACL.setPublicReadAccess(true); publicPost.setACL(postACL); publicPost.save(); @@ -248,11 +248,11 @@ const women = await query.find(); Associations involving a `Parse.User` work right of the box. For example, let's say you're making a blogging app. To store a new post for a user and retrieve all their posts: ```javascript -var user = Parse.User.current(); +const user = Parse.User.current(); // Make a new post -var Post = Parse.Object.extend("Post"); -var post = new Post(); +const Post = Parse.Object.extend("Post"); +const post = new Post(); post.set("title", "My New Post"); post.set("body", "This is some great content."); post.set("user", user);