Enable data insertion on a Meteor server without requiring login authentication

I am looking to develop an API that enables other apps to add new data. However, I have encountered an issue while attempting to do so. The error message "User id is required" appears because there is no logged-in user present when inserting new data. Is it possible to insert new data without a login, or is there a way to log in from the server side using the accounts-password package? How can I make this process work smoothly?

Server-side code snippet:

Picker.route('/createFood/:title', function(params, req, res, next) {
console.log('-> params : ',params);
let username = (new Date()).getTime().toString();
function createFood() {
  Fiber(function() {
    console.log("-> username : ",username);
    let acc = Accounts.createUser({
      username: username,
      email: username +'@foodie.com',
      password: username
    });  
  if (acc) {
      console.log("-> acc : ",acc);
      // Meteor.call("setUserId", acc);
      Menus.insert({
        title: params.title,
      }, function(err, foodId) {
        console.log("-> abs : ",Meteor.absoluteUrl());
        console.log("-> err : ",err.message);
        console.log("-> foodId : ",foodId);
        let code, result;
        if (err) {
          code = 500;
          result = {
            error: err.message
          }
        } else {
          code = 200;
          result = {
            foodId: foodId,
          }
        }
        res.setHeader( 'Content-Type', 'application/json' );
        res.statusCode = code;
        res.end( JSON.stringify( result ) );
      })
    }

  }).run();
}
if (params.title)
  createFood(); 
});

Code snippet for the food model, where there is a userId owner specified:

if (Meteor.isServer) {
Menus.allow({
  insert: function() {
    return true;
  },
  update: function() {
    return true;
  },
  remove: function() {
    return true;
  },
  fetch: ['foodId'],
});
Menus.after.insert((userId, doc) => {
 ....
})
}

Answer №1

It is perfectly possible to add entries to the database even without being authenticated. The accounts package is not mandatory for this specific task.

The current implementation only allows insertion when a user is logged in, however, you can simplify it as follows...

function addFoodItem() {
      MenuItems.insert({
        itemName: data.itemName,

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

What is the solution to setting true and false equal to true in an AngularJS expression?

How can I determine if an input field has been touched and is empty, without using the built-in functions in Angular? <form-input is-invalid-on="isTouched && !gs.data.name || gs.data.name.length > 50"></form-input> If isTouched &am ...

Using Jquery colorbox to redirect or forward within the current colorbox container

I am facing a challenge with a colorbox that is currently loaded. I am looking for a way to redirect or forward to another page within the existing colorbox. window.location = href; does not seem to be effective in this situation. EDIT: To be more precis ...

``I'm having trouble getting the onchange event to function properly in a customized

After following a tutorial, I successfully created a custom select dropdown using the provided link. https://www.w3schools.com/howto/tryit.asp?filename=tryhow_custom_select However, I am facing an issue with the onchange event not working for the select ...

The JQUERY code for refreshing a div requires a timeout delay

I'm looking for a way to refresh a specific div on my website that's used for chat. Here's the code I currently have: var refreshId = setInterval(function() { $('#chat_grab').load('chat_grab.php?randval=' + Math.rand ...

Navigate to the AngularJS documentation and locate the section on monitoring data changes after a dropdown selection

Just starting out with AngularJS and Stack Overflow, so I hope I am asking this question correctly. I am working on a single-page application with editable text inputs. Two select drop-downs are used to control which data is displayed - one for time perio ...

Transforming an older React website with react-helmet-async

I am working on a React site that is client-side rendered and I want to use the react-helmet-async module (version 1.0.7). Here's my scenario in the React app: /public/index.js: <head> <title>My title in the index file</title> ...

What is the method to determine the number of keys that have the same value in a JavaScript object?

My goal is to achieve functionality similar to this: var data = [ { tag:'A', others:'Abc' }, { tag:'B', others:'Bbc' }, { tag:'A', others ...

Exploring the Potential of CSS Styling within Vue.js

I am in the process of creating a website and I am looking for a way to manage my styles through Vue. I want to be able to utilize CSS with Vue, as the style of .skill-bar serves as the background of the bar, while .skill-bar-fill represents the green fil ...

Exploring the variable scope in Node.js with a focus on separating routes

My routing configurations are stored in an external folder. Find them in the ./routes directory This is how I set up my routes within the server.js file: app.get('/', routes.index); app.post('/validation', register.valid); The reg ...

Launching various modals on marker click

I'm having an issue where I need a different modal to be displayed depending on the name in the markerSet array. Currently, the if/else statement is always returning the same modal. Take a look at the if statement in my JavaScript code below. The nam ...

Remove buttons from carousel elements in React Multi-Carousel

Is there a way to hide the arrows in the react-multi-carousel component? https://i.stack.imgur.com/V1nix.png ...

Is there a way to serialize a dynamically loaded element with jQuery?

So here's the situation: I have a list of tags that needs to be updated using an ajax call. First, I clear out the <ul> that holds the tags. Then, with the response from the ajax call, I populate the <ul> with new <li> elements re ...

Implementing ExpressJS with MongoDB on a MERN Development Stack

After configuring my ExpressJS & MongoDB client and running Nodemon, I consistently encounter the following warning: "DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the ...

The jQuery plugin functions smoothly when running on localhost, but it causes issues with the background image when deployed on the web

I created a compact plugin to show a cookie message. While testing it on my local machine, everything functioned smoothly without affecting any web pages. However, once I transferred the files to the server, I encountered issues such as: A background ima ...

My goal is to prevent users from using the Backspace key within the input field

Let's say we want to prevent users from using the backspace key on an input field in this scenario. In our template, we pass the $event like so: <input (input)="onInput($event)"> Meanwhile, in our app.component.ts file, the function ...

What is the best way to integrate jQuery Masonry with ES6 modules?

Attempting to utilize the npm package https://www.npmjs.com/package/masonry-layout Following the installation instructions, I executed: npm install masonry-layout --save Then, in my file, import '../../../node_modules/masonry-layout/dist/masonry.p ...

Leveraging data schemas to manage the feedback from APIs

I am curious about the benefits of modeling the API response on the client side. Specifically: First scenario: const [formData, setFormData] = useState(null); ... useEffect(() => { const callback = async () => { try { const fetchDa ...

Retrieving the selected value from an added dropdown list using jQuery

Could someone please guide me on how to retrieve the selected value from an appended select list using jQuery? Any assistance would be greatly appreciated. Thank you in advance. var wrapper1 = $(".column1"); array1 = ["sample1", "sample2", "sample3"]; ...

"Everything is running smoothly on one REST endpoint, but the other one is throwing a CORS error

I am currently working on a project that involves a React client app and a Django server app. The React app is running on port 9997 and the server API is on port 9763. While the frontend is able to access some APIs successfully, there are some APIs that ar ...

Using ObjectIds in HTTP requests with MongoDB

I'm currently facing some challenges with understanding how HTTP request queries function. My goal is to send an array of ObjectIDs in a http request query to my express server. const query = { ids: [ new ObjectID(), new ObjectID(), ], }; ...