Is it possible to execute a MongoDB insert within a Meteor method?

I've encountered an issue in my Meteor app where a Meteor method takes a collection as a parameter and attempts to run the mongo insert command on that collection to create a new document. The code is set to run every 10 seconds using setInterval.

The collection is defined as:

My_Collection_Name = new Meteor.Collection('my_collection_name');


Server code:

var collection = My_Collection_Name;
var data = [1,2,3,'a','b','c'];
Meteor.call('createDocument', collection, data);


Method:

Meteor.methods({
  createDocument: function(collection, data) {
    collection.insert({
      data: data
    });
  }
});


However, when running the code, the console displays the following error:

I20141030-14:58:06.716(-4)? Exception in setInterval callback: TypeError: Object #<Object> has no method 'insert'

Why is this happening? Can a collection be passed in as a parameter in this context? Any insights would be appreciated. Thank you!

Answer №1

The scenario here involves having separate collections on the client and server sides, as detailed further in Understanding Meteor publish/subscribe. It's not advisable to depend solely on the private _collection field. Instead, it's recommended to pass the collection name as a string to Meteor.call, ensuring consistency in variable naming for the collection on the server, and then accessing the collection by its name within the global object on the server:

// on the client:

MyCollection = new Mongo.Collection('record-set-name');  // as defined on the server through .publish()
Meteor.call('createDocument', 'MyCollection', data);

// on the server:
MyCollection = new Mongo.Collection('collection-name-in-mongo');
Meteor.methods({
  createDocument: function(collectionName, data) {
    global[collectionName].insert({
      data: data
    });
  }
});

This methodology is employed by meteor-autocomplete for transmitting collection names from the client to the server, demonstrating its practicality in application. (source)

For a deeper understanding of the interplay between collection names and variables in Mongo, refer to Understanding Meteor publish/subscribe.

Answer №2

Upon closer examination of the collection object, I discovered that it contains a nested object called _collection which houses functions such as insert, update, etc. By making the following adjustment to the code, you can successfully execute Mongo commands on a collection parameter within a Meteor method:

Meteor.methods({
  addNewDocument: function(collection, content) {
    collection._collection.insert({
      data: content
    });
  }
});

Answer №3

In this scenario, the variable collection seems to represent a collection name. If you are dealing with multiple collection names, you can handle them in a similar manner within server methods. Here's an example:

Meteor.methods({
  createDocument: function(collection, data) {
    if(collection === "firstcollection") {
      firstcollection.insert({
        data: data
      });
    } else if(collection === "secondcollection") {
      secondcollection.insert({
        data: data
      });
    }
  }
});

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

Organize the array object by roles using mapping and grouping techniques

Given an object array with roles as keys and values, I want to group them according to the roles assigned. Here is the sample data: { users: [ { firstName: 'Will', lastName: 'Jacob', email: '<a href="/cd ...

Creating a javascript function to update content on click

Recently, I've been designing a webpage and encountered an issue. I want the text in a specific area to change whenever a user clicks on a link. Below is the code snippet related to the section I want to modify using a JavaScript function. <div id ...

Displaying data as a JSON object in AJAX requests within Grails

I am looking to automatically populate employee details when an employee number is entered. Within the controller, I am executing a method that returns a JSON object: Gson gson = new Gson(); System.out.println(gson.toJson(objEmp)); return gso ...

finding the node version in a code repository

Is it possible to determine the targeted node version (4 or 6) of a Node.js application by examining its code? I'm currently reviewing this: https://github.com/jorditost/node-postgres-restapi ...

Tips for preloading a script in nextjs

I'm having trouble incorporating a script into my website. The issue is that the script doesn't load properly the first time the page loads, but after a few refreshes, it works and the responsible iFrame shows up. I've attempted several di ...

Guide to making an `Ajax Login` button

I am interested in creating a SIGN IN button using ajax. Specifically, I want it to display something (such as welcome) on the same page without refreshing it. This is the progress I have made so far: update2: <form id="myForm" onsubmit="return signi ...

Is there a way to rearrange the selectpicker selection based on the user's choice?

I'm in the process of setting up a selectpicker that allows users to choose multiple options from a dropdown list. The challenge is that the values extracted by my backend need to be in the order of user selection, rather than the original order of th ...

A web application using JavaScript and Node.js with a focus on creating a REST

After extensive research, I am eager to develop a web application using JavaScript and Node.js with an SQL back-end. However, the abundance of frameworks and tools available has left me feeling overwhelmed. While I have identified some that I would like to ...

Craft a hierarchical JSON structure out of a different nested JSON object [PAUSE]

Looking to transform an existing JSON object into a new object structure. Here is the current JSON object: { "name": "Parent", "children": [ { "name": "Child1", "children": [ { "name": "GrandC ...

Retrieving an Ajax response by using form.submit() and sending it to PHP

After spending hours trying to mix a form.submit() call with a jquery/ajax call in order to receive a response from my php login script, I am at a loss. Despite looking through countless posts and examples on the same topic, I can't seem to find a sol ...

Is it possible to incorporate a counter into a MongoDB query?

I am looking to enhance my query results by adding a counter to each matching document. For example, I'd like the first document to have a counter value of 1, the second document to have a counter value of 2, and so on. Below is a snippet of the data ...

Providing secure access to Apostrophe-CMS S3 assets and attachments via HTTPS

Currently, I am utilizing Amazon S3 to deliver both my static assets and user uploads within the context of apostrophe-cms. While my site is loading via https, all of my assets appear to be loading using http. I have set up a cloudfront distribution at th ...

Place the script tags within the window.load function inside the head section

<head> <script type="text/javascript"> $(window).load(function() { // <script src="js/external.js"></script> // }); </script> </head> Is it possible to insert a script tag(< script src="js/exte ...

Is there a way to identify if a user clicks on the scrollbar within my div element?

Is there a way to detect when someone mouses down on the scrollbar of a div element with scrollbars? ...

There will be no pop-up notification displayed if the product is already in the cart

When a product is added to the cart, the following code is used: addproduct(itemId) { this.showLoading = true this.$http.post('/shampoo', {'item': itemId}).then((response) => { swal({ title: "Success!", ...

Embed the variable directly within the JSON structure

My goal is to dynamically create a JavaScript object using object initializer notation, but with keys taken from a config object. Instead of the traditional method: var obj = { 'key' : 'some value' }; I envision something like this: ...

Transmitting data (item) with a 404 error code (JavaScript)

Exploring the world of NodeJS and Nuxt, I am eager to master the process of transmitting an object from the front-end client to the back-end server and receiving a response. Imagine sending a basic registration object like this: registerInfo: { username ...

Tips for ensuring the CSRF token functions properly on the browser when utilizing Django and React

Apologies in advance if this question seems beginner-friendly, but I have developed an application with Django backend and React frontend. I am currently working on implementing the CSRF token for the post request on the create endpoint using the code snip ...

Unspecified data transfer between child and parent components

I'm working on implementing a file selection feature in my child component, but I'm facing difficulties passing the selected file to the parent component. I'm struggling to find a solution for this issue and would appreciate some guidance. W ...

Transform spaces into %20 from an HTML input field by utilizing JavaScript or jQuery

Hi there, I'm encountering an issue with the input field on my website where users can enter search terms. I am currently extracting the user's input value and adding it to a URL string. jQuery("#searchButton").click(function(){ var simpl ...