docs/api/javascript/transformations/with_fields.md at master · rethinkdb/docs · GitHub
Skip to content

Latest commit

 

History

History
55 lines (44 loc) · 1.53 KB

File metadata and controls

55 lines (44 loc) · 1.53 KB
layout api-command
language JavaScript
permalink api/javascript/with_fields/
command withFields
io
sequence
stream
array
array
related_commands
pluck hasFields without
pluck/
has_fields/
without/

Command syntax

{% apibody %} sequence.withFields([selector1, selector2...]) → stream array.withFields([selector1, selector2...]) → array {% endapibody %}

Description

Plucks one or more attributes from a sequence of objects, filtering out any objects in the sequence that do not have the specified fields. Functionally, this is identical to hasFields followed by pluck on a sequence.

Example: Get a list of users and their posts, excluding any users who have not made any posts.

Existing table structure:

[
    { 'id': 1, 'user': 'bob', 'email': 'bob@foo.com', 'posts': [ 1, 4, 5 ] },
    { 'id': 2, 'user': 'george', 'email': 'george@foo.com' },
    { 'id': 3, 'user': 'jane', 'email': 'jane@foo.com', 'posts': [ 2, 3, 6 ] }
]

Command and output:

> r.table('users').withFields('id', 'user', 'posts').run(conn, callback)
// Result passed to callback
[
    { 'id': 1, 'user': 'bob', 'posts': [ 1, 4, 5 ] },
    { 'id': 3, 'user': 'jane', 'posts': [ 2, 3, 6 ] }
]

Example: Use the nested field syntax to get a list of users with cell phone numbers in their contacts.

r.table('users').withFields('id', 'user', {contact: {phone: "work"}).run(conn, callback)