Issue with Angular and Meteor: Array is not defined

Currently, I am developing a web application using Angular and Meteor. The integration of Meteor's reactivity with Angular models is working smoothly, except when dealing with arrays.

// Retrieve sentence
$scope.sentence = $meteor.object(Sentences, $stateParams.sentenceId);

// Fetch related sentences
$scope.relatedSentences = $meteor.collection(function() {
   return Sentences.find({_id: { $in: $scope.sentence.relatedSentences }}); 
});  

An error message appears in the JavaScript console:

Error: $in needs an array
    at Error (native)
    at Object.ELEMENT_OPERATORS.$in.compileElementSelector     (http://localhost:3000/packages/minimongo.js?af9eb9d7447544ca9b839a3dcf7ed2da2209b56c:1894:15)
    at http://localhost:3000/packages/minimongo.js?af9eb9d7447544ca9b839a3dcf7ed2da2209b56c:1576:19
    at Function._.each._.forEach (http://localhost:3000/packages/underscore.js?    0a80a8623e1b40b5df5a05582f288ddd586eaa18:164:22)

In the Mongo / Meteor console:

meteor:PRIMARY> db.sentences.find({_id: "sp75iWPNqpbp2ypmy"});
{ "_id" : "sp75iWPNqpbp2ypmy", "sentence" : "Here is sentence 1 ", "language" : "en", "level" : "A1", "public" : true, "relatedSentences" : [ "wNs4ByDq7t396WLM3" ] }

And:

meteor:PRIMARY> db.sentences.find({_id: { $in: [ "wNs4ByDq7t396WLM3" ] }});  
{ "_id" : "wNs4ByDq7t396WLM3", "sentence" : "Here is sentence 0 ", "language" : "en", "level" : "A1", "public" : true, "relatedSentences" : [ ] }

I have temporarily disabled the failing find function and displayed the objects in HTML:

$scope.sentence = $meteor.object(Sentences, $stateParams.sentenceId);
$scope.test = typeof $scope.sentence.relatedSentences;

Sentence: {{sentence}}<br/>
Related: {{sentence.relatedSentences}}<br/>
Typeof: {{test}}

The results show:

Sentence: {"autorunComputation":    {"stopped":false,"invalidated":false,"firstRun":false,"_id":47,"_onInvalidateCallbacks":  [null,null],"_parent":null,"_recomputing":false},"_id":"oFMp7swYyQsXkYsKz","sent ence":"Here is sentence  2","language":"en","level":"A1","public":true,"relatedSentences":    ["wNs4ByDq7t396WLM3"]}
Related: ["wNs4ByDq7t396WLM3"]
Typeof: undefined

The Array is shown as undefined, though it is clearly present in the full object. What could be the issue?

EDIT: Upon testing this on Firefox, the output is:

Related: ["wNs4ByDq7t396WLM3"]
Typeof: object 

For more information, refer to the related issue here.

Answer №1

$scope.test gets bound only once during the initial code execution. Data binding is not implemented, so even if there are changes in $scope.sentence.relatedSentences, the value of test will remain the same. The main issue here is that $scope.sentence.relatedSentences is populated asynchronously.

A similar situation occurs with $scope.relatedSentences as you are trying to set it before $scope.sentence.relatedSentences is fully loaded. One way to handle this is by using .subscribe on the return value from .object and setting it once the data becomes available.

$scope.sentence.subscribe().then(function () {
    $scope.relatedSentences = $meteor.collection(function() {
        return Sentences.find({_id: { $in: $scope.sentence.relatedSentences }}); 
    });  
});

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

Preventing a bootstrap data target from opening based on certain conditions

<button type="button" id="submitButton1" name="submitButton1" class="btn btn-primary waves-effect waves-light" ng-click = "validateAndSaveData('upload')" value="Upload Documents" data-target="#myModal1" data-t ...

A helpful guide on Sending parameters to a route using an object

I am attempting to transfer data with passing parameters from page1 to page2. Below is the code snippet from page1 : axios({ method: 'post', url: "http://127.0.0.1:8000/api/masuk", data: { ...

Transform Tree Hierarchy into Two-Dimensional Array

Looking to transform a tree-like structure into a 2D array. Defined by the following person class: public class Person { public string Name { get; set; } public List<Person> Children { get; } = new List<Person>(); } With data populat ...

I encountered a segmentation fault when attempting to pass a 2D array into a function in C

As a beginner programmer delving into learning C, I am faced with a challenge. My goal is to read the dimensions of an array from the user, create the array using malloc, and then pass the created array inside a function. This function should find the mini ...

Changing a button's value on click using PhoneGap

I've been working with phonegap and came across an issue with my buttons setup like this: <input id="my_button" type="button" onclick="my_function();"/> The goal is to capture the click event and change the button's value, my_function ( ...

Incorporating string input values into a function

I am currently working on a function that retrieves the value of an input upon clicking a button. My goal is to then have another event that will incorporate that value into a function when the button is clicked. var getInput = function() { $('#inpu ...

Tabulator - Enhancing Filter Results Using a Second Tabulator

I've implemented a Tabulator that displays search results, here is the code: var table = new Tabulator("#json-table", { layout:"fitDataFill", //initialFilter:[{field:"title", type:"!=", value:"ignoreList.title"}], ajaxURL:tabUrl, ajax ...

Ways to prevent form submission while awaiting a server response in JavaScript

I am working on a form that submits data to a JSP page with Java code. <form method="POST" id="form1" action"<%=login%>"> <input id="btn" type="submit" value="Log in" /> However ...

Is the _id of a newly inserted document in MongoDB always larger than that of an older document?

Can anyone explain the process MongoDB uses to calculate the "_id" field? It appears to be incremental in nature. I'm curious if sorting by the "_id" field is a reliable way to sort documents based on their insertion time. ...

Troubleshooting: Javascript success callback not executing upon form submission

A snippet of my JavaScript looks like this: $(document).ready(function(){ $("#message").hide(); $("#please_wait_box").hide(); $("#updateinvoice").submit(function(e){ $("#message").hide(); ...

Using Leaflet JS to add custom external controls to your map

Is there a way to implement external controls for zooming in on an image? I've searched through the documentation, but haven't been able to find a clear solution. HTML: <div id="image-map"></div> <button id="plus">+</butto ...

Testing Jasmine asynchronously with promise functionality

During my Jasmine testing with angular promises, a question arose regarding timing. I came across a post at Unit-test promise-based code in Angular, but I still need some clarification on how it all functions. The concern is that since the then method is ...

Choose a particular text node from the element that has been selected

Can anyone provide guidance on how to extract the text "Items Description" from the following HTML snippet using jQuery? <div class="items"> "Items Description" <ul> <li>1. One</li> <li>2. Two</li&g ...

The scrolling action triggered by el.scrollIntoViewIfNeeded() goes way past the top boundary

el.scrollIntoViewIfNeeded() function is used to scroll to element el if it's not within the visible browser area. Although it generally works well, I have encountered some issues when trying to use it with a fixed header. I have provided an example s ...

Dreamweaver seems to struggle to properly execute the identical code

There are times when I transfer javascript code from jsfiddle to Dreamweaver and find myself frustrated. Two documents with seemingly identical javascript don't function the same way. In document A, I have this code: <script> alert('test& ...

Steps for initializing and loading the Ace editor:

I've been attempting to utilize the Ace code editor library (), but I'm encountering some issues. The embedding guide suggests that the required js files should be loaded from Amazon's CDN. <script src="http://d1n0x3qji82z53.cloudfront.n ...

Error in MEAN CRUD operation cannot be determined

{ text: undefined, done: false, _id: 529e16025f5222dc36000002, __v: 0 } PUT /api/todos/529e16025f5222dc36000002 200 142ms - 68b Encountering an issue while updating my CRUD todo list. Despite receiving a successful status code of 200 after submittin ...

Angular response object being iterated through in a loop

I am facing a challenge while trying to iterate through an array containing values that need to be displayed to the user. Despite receiving a response with the data, I am having trouble accessing and looping through the elements of the array using Angular. ...

If you want to use the decorators plugin, make sure to include the 'decoratorsBeforeExport' option in your

Currently, I am utilizing Next.js along with TypeScript and attempting to integrate TypeORM into my project, like demonstrated below: @Entity() export class UserModel extends BaseEntity { @PrimaryGeneratedColumn('uuid') id: number } Unfortun ...

Improving efficiency by saving and loading the form value using best practices

One of the challenges I'm facing is how to populate dropdown selections on a webpage without resorting to hard-coded procedures. The code snippet below illustrates the current setup: <td> <ui-select ng-model="user_profile.gender" require ...