Meteor: Allowing users to share their personal fields on their account

I am currently facing an issue with publishing "friends" from the users Collection. Within each account, there is a field named addressbook that stores all friend-ids. Unfortunately, when trying to publish this information, I only receive my own account (as a non-admin) when running Meteor.users.find().fetch() in the console. The output in the console looks like this:

I20140107-17:22:38.492(1)? ---------------------------------------[object Object]
I20140107-17:22:38.497(1)? [ { _id: 'X6XXyD64AW4CvXG6m',
I20140107-17:22:38.498(1)? createdAt: Tue Jan 07 2014 17:10:43 > GMT+0100 (CET)
I20140107-17:22:38.498(1)? emails: [ [Object] ],
I20140107-17:22:38.498(1)? services: { password: [Object], resume: [Object] },
I20140107-17:22:38.499(1)? username: 'test' } ]

addressbook data is not being displayed

Here's a snippet of the code in question:

Server-side:

Meteor.publish("users", function(){
    if (Roles.userIsInRole(this.userId, ["admin"]))
        return Meteor.users.find();
    else
        return Meteor.users.find({_id : this.userId}, {fields: {username: 1, id_:1, emails:1, addressbook:1, createdAt:1}});
});

Meteor.publish("friends", function(){
    var addressbook = Meteor.users.find({_id: this.userId}, {limit:1} , {fields: {addressbook:1}});
    console.log("---------------------------------------" + addressbook);
    console.log(addressbook.fetch());

    //return Meteor.users.find({_id :{ $in : addressbook}}, {fields : {username:1, emails: 1}});

Client-side:

Deps.autorun(function() {
    Meteor.subscribe("friends");
    Meteor.subscribe("users");
});

How can I successfully publish the users based on their ids stored in the addressbook field (or at least their emails and usernames)? Are there better ways to combine these publishes?

Thank you in advance!

Answer №1

There appear to be a couple of issues with the friends publish function you've written:

  1. When fetching a single document, you can simply use findOne without specifying a limit.
  2. The options for a find should be passed as a single object, like this:
    {limit: 1, fields: {addressbook: 1}}
  3. In order to access the values of a document, you need to fetch it first or use findOne.
  4. fetch is a method that is available on a cursor, not on arrays like addressbook.

It looks like you were heading in the right direction. You could try the following code snippet:

Meteor.publish('friends', function() {
  var addressbook = Meteor.users.findOne(this.userId).addressbook || [];
  return Meteor.users.find({_id: {$in: addressbook}}, {fields: {username: 1, emails: 1}});
});

Just a heads up - the friends publication won't reactively update if the addressbook changes. To achieve that, you may want to consider using a reactive join. Check out this question for more information.

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

"Node.js: The Importance of Rest for Optimal Performance

Imagine this situation: As part of my cron jobs, I am utilizing an external service that limits requests to every 3600 seconds. This service's API is similar to GetPersonForName=string. I have multiple people in my database and it's necessary to ...

HyperText Markup Language, Cascading Style Sheets, and JavaScript

In my div, I have a combination of icons and text. I'm trying to center only the text within the div, with two icons on the left and 4 to 5 icons on the right. Although I managed to position the icons correctly, I am having trouble aligning the text ...

What is the best method for saving a chosen radio button into an array?

I am currently developing an online examination system where questions are retrieved from a database using PHP and displayed through AJAX. I am facing an issue where I am unable to capture the selected radio button value and store it in an array. Despite e ...

Updating Vue.js Component Data

I have set up a basic Example Component which is bound to a Vue Instance as shown below: <template> <div class="container-fluid"> <div class="row"> <div class="col-md-8 col-md-offset-2"> < ...

Tips for implementing X-XSS-Protection: 1; mode=block in HTML

I'm struggling with where to place this piece of code in my existing code. Should it be added to the header section? <head> <meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" /> <title> ...

Having trouble organizing a list of objects based on changing keys

Below is the implementation of a custom pipe designed to sort records: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'sortpipe' }) export class SortPipe implements PipeTransform { transfor ...

"Encountering a hurdle while trying to launch a MongoDB and Express

After successfully running my express app locally with a mongoose connection, I encountered a problem when deploying to Heroku. An error message "Application Error" with status 503 appeared. Interestingly, when I deployed the app without the mongoose conn ...

Exploring nested hash maps within JavaScript

Having some trouble with creating a nested hash map in JavaScript (js), similar to the example below: let rooms = {}; rooms[roomNum][personName] = somethings; However, I keep encountering an error when attempting this: TypeError: Cannot set property &apo ...

Is there a way to dynamically modify the email content with the Gmail API using JavaScript?

I have received the message body and now I need to make some updates to it. When I try using this login/code, I encounter a 400 error. I believe the issue lies in the body parameter of the request. Can someone please assist me with this? var token = loca ...

Utilizing a unique index with GridFS can lead to the creation of orphan chunks

While working on uploading a file, I noticed that when there is a duplicate value in a metadata field that has a unique index in the Spring framework's GridFsTemplate, a MongoWriteException (E11000 duplicate key error) is thrown. However, even though ...

Looping through an array of data retrieved from the MS Graph API

When using node to call the MS Graph API with v1.0/users, the returned data shows a list of users in the following format after doing a console.log(users): { [ { displayName: "bob dole" }, { displayName: "steve st ...

Transforming data with D3.js into a string representation

Recently, I stumbled upon a function called "stringify" that seems like a fantastic tool for converting flat data into a Json format. If this function lives up to its potential, it could potentially save me countless hours of writing recursive code in ASP ...

What could be causing the return of undefined upon execution?

function updateTitle(title) { title = "updated title"; } var currentTitle = "original title"; currentTitle = updateTitle(currentTitle); console.log(currentTitle) I'm just starting to learn JavaScript and I'm curious about why this code behav ...

Callback is triggered after ng-if removes the directive from the scope

A scenario on my page involves an angular directive nested within ng-if. I've developed a service that features a function, let's name it functionX, capable of accepting a callback as an argument. Whenever the ng-if condition becomes true, the ...

Peer-to-peer Ajax image sharing

Currently, I'm utilizing Ajax to fetch images from a remote server. Initially, I attempted this by directly using the URL of the remote server - resulting in the returned image being a string (given that's how Ajax communicates). To rectify this, ...

The functionality to import JSON data into Google Spreadsheets is compromised when the API includes the characters " | "

I am attempting to bring JSON data into Google Sheets using a Wikidata API. However, one of the symbols utilized in this API is the vertical bar: |. It serves as an "and". For instance, if I wish to import data in BOTH English and Greek, then I need to us ...

What is the method for creating a new array of objects in Typescript with no initial elements?

After retrieving a collection of data documents, I am iterating through them to form an object named 'Item'; each Item comprises keys for 'amount' and 'id'. My goal is to add each created Item object to an array called ' ...

Using PHP to auto populate HTML form

In my application, I have two forms. The first form takes user input with a post action and runs a SELECT query with a WHERE clause using PHP in the backend. The retrieved value is stored in a session variable to make it global. I then display this session ...

How can we achieve the same functionality as React Native's { flex: 1 } in React JS?

I've been diving into React Native development, and now I'm exploring React.js for web applications. However, I'm facing a challenge in creating a simple View that takes up the entire screen to begin experimenting with different components. ...

Having trouble making the swing effect trigger on mouseover but not on page load

I am trying to achieve a swinging effect on mouseover only, not on page load. Below is the JS code I have: (function swing() { var ang = 20, dAng = 10, ddAng = .5, dir = 1, box = document.getElementById("box"); (function setAng(ang){ ...