Storing User Input Array into MongoDB Collection

I need help with integrating user prompts into my social networking site. I want to gather responses in an array and then insert the entire array at once into a MongoDB database. While I am able to prompt users, I am facing challenges when it comes to inserting the array. Below is the code snippet:

'click #creator': function(event){

  var channelName = prompt('Enter The Channel Name');
  var howmany = +prompt('How many people do you want? (max 10)');  
  var users = [];  
  var arr = [];  // define our array

  if(howmany > 1 && howmany<10){
    for (var i = 0; i < howmany; i++) {              // loop 10 times
      arr.push(prompt('Enter a user' + (i+1))); // push the value into the array
    }

    users = arr.join('"," ');     
    Meteor.call('addChannel', channelName, users);
  }
}

Here is the insertion piece of the code:

 Channels = new Mongo.Collection('channels');
 Meteor.methods({
   addChannel: function(channelName, users){
     if(!Meteor.userId()) {
       throw new Meteor.Error('not-authorized', 'you are not signed in');
     }

     var username = Meteor.user().username;

     Channels.insert({
       name: channelName,
       created: new Date(), 
       members: $push: {users} 
       createdBy: username
     });
   },
 });

Answer №1

If you are inserting data into an array, like in the case of 'users', there is no need to use the '$push' method. Also, avoid pushing an empty object '{}'

Channels.insert({
  name: channelName,
  created: new Date(),
  members: users,
  createdBy: username
});

When working on the client side, remember to skip using 'arr.join()' as it converts the array into a string. Instead, pass the array directly to the function.

Meteor.call('addChannel', channelName, arr);

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

Spin a dice counter and victory is claimed when the player lands on the lucky number of 21

Looking to create a dice counter game where you roll the dice as many times as you want and aim to hit 21 to win. If you go over 21, the game will notify you that you've lost and prompt you to try again. I'm having trouble figuring out how to dis ...

When using MongoDB's distinct feature on an array of embedded documents, the index is not utilized

Imagine I have a set of documents like this one, featuring the stock field containing an array of embedded documents: { _id: 1, item: "abc", stock: [ { size: "S", color: "red", quantity: 25 }, { size: "S", color: "blue", quantity: 10 }, ...

Is it possible to extract only the time from a date and time using angular-moment library?

I am trying to display only the time from a date. My code looks like this: $scope.sample_time = "September 14th 2017, 1:00:00 pm"; What I want in my view is to show just the time, for example 1:00 pm. I attempted to use angular-moment, with something li ...

Arrangement featuring two distinct types of tiles

Looking for a way to achieve this layout using just CSS or a combination of CSS and a little JS. Click on my avatar to see the reference image enlarged =) I've tried using floats and display options but haven't been successful. Take a look at htt ...

Exploring the Geospatial Overlap of Two Polygons in MongoDB

Is it possible to use a mongodb geospatial query to retrieve location data that meets the following criteria? Retrieving all locations that fall within the intersection of two boxes or any two polygons in general. For example, is it feasible to only out ...

I am interested in dynamically changing the texture/material of a .obj file during runtime with the click of a button using three.js

Whenever I try to load my model and change its texture, the model doesn't load and nothing appears on the screen. I am new to three.js/webgl languages and javascript. Can someone please provide me with the correct information to move forward? Below is ...

Unexpected behavior in Select2 integration with AngularJS

I've been having trouble getting the select2 library to work properly with AngularJS select elements. I put together a small jsFiddle with the same option values that I'm using in my project. However, it seems like the select2 functionality is ...

What is the connection between {{result}} and $scope.result within AngularJS?

I comprehend the concept of binding a model to an element. An example would be... <pre ng-model="result">. This connection is established through the $scope.result variable. However, how are these two related? {{result}} $scope.result = data; ...

Exploring the process of defining directives with Vue 3's composition API

How can directives be defined and used in Vue3's composition API using the new syntactic sugar in SFC <script setup> format? In the past, with the options API, it looked something like this: import click_outside from "@/directives/click-out ...

Replacing Google Maps with downloaded maps for navigation

The issue at hand is that I have created a webpage that displays multiple Points of Interest (POI) on a map. The map is powered by Google Maps and works perfectly as long as I have access to wifi. However, I am looking for a way to preload the map on my la ...

Is it possible to leverage specific client-side Javascript APIs on the server-side?

Exploring APIs designed for web browsers that require their .js code to return audio streams. In a broader sense, these APIs provide byte streams (such as audio) for playback in the browser. Is it possible to use these APIs in server-side Javascript frame ...

Could you provide some guidance on how to properly test this AngularJS code using Jasmine?

Here is a simple function I have: wpApp = angular.module('wpApp', ['ngRoute']); wpApp.controller("ctrlr", function($scope) { $scope.message = 'This is the page'; }); I am attempting to test it using Jasmine with this sp ...

Guide to setting up an object array in JavaScript with unique child elements and no duplicate values

I have an array that looks like this: sampleArray = ["x", "y", "z". "a.b", "a.b.c", "a.b.d", "a.e.f", "a.e.g"] However, I am aiming to transform it into the following structure, or something similar to it: newArray: [ { "x": [] }, ...

What options do I have for personalizing this Google Bar Graph?

I am currently working on creating a Google bar chart. You can view my progress here: http://jsfiddle.net/nGvdB/ Although I have carefully reviewed the Google Bar Chart documentation available here, I am struggling to customize the chart to my needs. Spec ...

The Vue.js 2 router is exclusively pulling components from the navigation bar, rather than directly from the URL

After selecting a page from the menu, the correct component loads. However, directly accessing the page URL does not display the content. This is the main template (which contains the menu): <template> <div class="row"> <div cl ...

Error in vue.js: Unable to call this.$emit as it is not a function

export default { mounted() { setTimeout(function() { this.$emit('onLoad') }, 4000); } } //views/Load.vue I want to redirect to another page after the page has been accessed for 4 seconds. <template> <d ...

Develop a gallery similar to YouTube or Vimeo

Is there a way to display a collection of SWF movies in a single DIV, with one SWF already set as the default? Something like a photo gallery but for SWFs. I would like to implement this using JQuery. Any suggestions or tips on how to achieve this? ...

Cloudflare SSL Error 522 Express: Troubleshooting Tips for Res

After setting up my express project using express-generator, I decided to make it work with a cloudflare SSL Certificate for secure browsing over https. My express app is running on port 443. Despite my efforts, when I try to access the domain, I encount ...

node/javascript - extracting information from a file stored locally

I am grappling with what seems like a simple issue while going through Eloquent Javascript. In the context of the "Mother-Child Age Difference" exercise 5-2, I am facing confusion. The necessary data is present in a file named ancestry.js, which I have sav ...

Manipulating child elements in XML, JavaScript, and jQuery – the possibilities are endless!

I have a good grasp on how to extract elements and write them to a document in JavaScript using the HttpXMLRequest object. However, I am struggling to find resources that explain how to modify it further. I believe part of the issue is that I am unsure of ...