Determine the presence of a value within an array in mongodb

How can I determine if the current Meteor.user()._id exists in the "favoritedBy" array?

If true, display "Your favorite", if false, display "Not your favorite".

Here is an example document in MongoDB:

{
  "_id" : "W5WwAZatorDEb6DNP",
  "createdBy" : "aTmb64zNGSyeDYFJZ",
  "favoritedBy" : [ 
      "X594baqWYZiJqA3Qg",
      "fgk234m2dkD229d12"
  ]
}

Assume that Meteor.user()._id returns X594baqWYZiJqA3Qg.

How can I perform a true/false check on this?

I attempted the following code:

isFavorite: function() {
    var user = Meteor.user()._id;
    return Posts.find({favoritedBy: user});
 }

In the template:

{{#if isFavorite}}
    Your favorite
{{else}}
    Not your favorite
{{/if}}

However, the code does not seem to work properly, as it always displays "Your favorite", even when the current Meteor user id is not in the array.

Any suggestions?

Answer №1

One way to determine if a user has favorited something is by using the following JavaScript function:

isFavorite: function() {
    var user = Meteor.user()._id;
    return Posts.find({favoritedBy: user}).count() > 0 ? true : false;
 }

The count() method in this function will return the number of documents that match a specific query. By checking if this count is greater than zero, the function uses a ternary operator to return either true or false based on the result.

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

Typeahead in Angular is failing to function properly after using the $compile method

I have made some adjustments to the popover directive in order to include files and $compile them. While I've managed to make ng-repeats function properly, I'm facing issues when trying to add a typeahead feature. angular.module("app").directive ...

Use jQuery to smoothly scroll a div

I created a container using a <div> element which is divided into 3 inner divs. The first two inner divs are meant to serve as previous and next buttons, with ids of prev and next respectively. At the bottom, there are 3 more inner divs, each with un ...

Load information from a JavaScript object when the user clicks dynamically

My challenge involves utilizing a JavaScript object that contains video information such as title and source URL. Within my HTML, I have image placeholders and the goal is to trigger a modal pop-up (using Twitter Bootstrap modal) of the specific video when ...

Is it not possible to change node labels in D3.js after clicking on a node?

After being inspired by this link, I successfully created a basic network visualization app using D3.js. The app reads node names from a textarea on an HTML page and then constructs a network where all nodes are interconnected. All the relevant code can ...

Tips for including a Places Autocomplete box within an InfoWindow on Google Maps

I am currently working with the Google Maps Javascript API v3 and I am facing a challenge. I want to integrate a Places Autocomplete box inside an InfoWindow that pops up when a user clicks on a marker. I have successfully created an autocomplete object a ...

Is Restangular taking forever to resolve the promise?

Just starting out with JavaScript and AngularJS, and this particular issue has me stumped. Requirements A RESTful service that retrieves data from the backend AngularJS 1.2.21 and Restangular 1.4.0 being used An AngularJS controller tasked with requesti ...

How can I align Javascript output vertically in the middle?

I am currently facing an issue with a JavaScript clock displaying in a narrow frame: <!DOCTYPE html> <HTML> <HEAD> <TITLE>Untitled</TITLE> <SCRIPT> function checkTime(i) { if (i < 10) { ...

Insert a design layout into a text entry box

Currently developing an application with AngularJS and seeking a solution for adding a "template" to an HTML input field similar to a placeholder. Specifically, I have a date-field requiring user input in the format of dd/MM/yyyy or through a datepicker se ...

Google Chrome's development tools are unable to detect the manifest

I have a file named manifest.json, and I included it in my HTML using <link rel="manifest" href="./manifest.json">. Despite everything seeming correct, Chrome developer tools are unable to detect my manifest file! This is the content of my manifest ...

Showing both SubTotal and Total simultaneously in a JavaScript powered interface

Recently diving into Javasript, I came across the code snippet below from a different source that I tweaked to suit my needs. My goal is to show the subtotal in the third column for each benefit while displaying the total of the entire form. However, I&apo ...

Loop through an array of objects, then store each one in MongoDB

If I receive an Array of Objects from a Facebook endpoint, how can I save each Object into my MongoDB? What is the best way to iterate over the returned Array and then store it in my mongoDB? :) The code snippet below shows how I fetch data from the Face ...

Converting Arrays into Objects with Multiple Dimensions

I have been attempting to transform this complex array into an object. However, I am facing an issue where only the second part of the array is being saved in the object, while the first part is missing. Is there a way to ensure that the entire array gets ...

What are the best methods for creating genuinely random and highly secure session IDs?

I am looking to develop session middleware for Express, however, I am unsure about generating random and secure session IDs. How do larger frameworks like Django and Flask handle this issue? What would be the best approach for me to take? ...

What could be causing the lack of updates in my shared service across all components?

I have implemented an Angular2 app where I am initializing an authentication service called LocalStorage which I want to be accessible across all my components: bootstrap(AppComponent, [ ROUTER_PROVIDERS, LocalStorage ]); The definition of the Lo ...

The function "element.join" is not a valid function

Currently, I am working on a project where I need to write a list of IDs into an external file using Node.js. Despite successfully creating the file with the nodejs file system and attempting to write into it, my program crashes and displays the error mess ...

The prompt "npm run build" command resulted in a 126 Vercel exit status

While attempting to upload my website with Webpack to Vercel from the repository, I encountered an error during the build process: Skipping build cache, deployment triggered without cache. Cloning completed: 2.089s Running "vercel build" Vercel CLI 31.2.3 ...

Is there a way to delete an Object from a MongoDB array without using $pull?

I'm in the process of developing a social media application, and I have created a route that allows users to like posts. However, I want the functionality such that if a user has already liked a post and clicks the "like" button again, it should remov ...

Guide to retrieving RabbitMQ queue messages in Vue.js application

I am currently working on a project using Spring Boot to publish messages to RabbitMQ and then push them to a queue. I also have a Vue.js frontend application that needs to consume these messages from the RabbitMQ queue. Despite searching online, I haven ...

Extending a universal design concept to a new theme within the MUI (Material UI) framework

I have implemented MUI's ThemeProvider and set up a Themes.js file. Within this file, I have defined the globalTheme for managing global styles such as typography and border-radius. My intention is to extend the properties of globalTheme to both light ...

The browser is not showing JavaScript alerts and prompts when they are called inside a function

/*I am attempting to run a color guessing game in my browser, but when I try opening the code in Chrome, it doesn't work. Any suggestions or ideas would be greatly appreciated.*/ var colors = ["Aqua", "Black", "Blue", "Brown", "Coral", " ...