Retrieving the user_id in Angular-Fullstack upon successful creation

When creating users, I am trying to retrieve the ID of the newly created user. However, I am facing difficulty getting it through the callback function. Here is what my current setup looks like:

controller.js:

Auth.createUser({
        name: this.user.name,
        email: this.user.email,
        password: this.user.password,
      }, function (err, user) {
        console.log(user); // Only returns 'name', 'email', 'password', not the '_id'
}

auth.service.js:

/**
     * Create a new user
     *
     * @param  {Object}   user     - user info
     * @param  {Function} callback - function(error, user)
     * @return {Promise}
     */
    createUser(user, callback) {
      return User.save(user, function(data) {
        $cookies.put('token', data.token);
        currentUser = User.get();
        return safeCb(callback)(null, user);
      }, function(err) {
        Auth.logout();
        return safeCb(callback)(err);
      })
        .$promise;
    },

EDIT: If I try using the API endpoint:

$http.post('/api/users/', {
        name: this.usr.name,
        email: this.usr.email,
        password: this.usr.password
      })

The returned object is:

Object { data: Object, status: 200, headers: headersGetter/<(), config: Object, statusText: "OK" }

Within the 'data' property, there is:

data {
    token: eyJhbGciOiJ...Vs3Ng14ycQA
    __proto__: Object 
}

As a result, I am unable to retrieve the user information. Any assistance on how to overcome this issue would be greatly appreciated. Thank you in advance.

Answer №1

It seems like you may have misunderstood a concept, which is making your task more complicated. Let me try to clarify it for you.

If you have a promise that needs to be returned, you can use the options resolve and reject. This means that when either resolve or reject is called, you can handle it in the then...or...catch call.

Auth.createUser({
        name: this.user.name,
        email: this.user.email,
        password: this.user.password,
      }, function (err, user) {
        console.log(user); // Only return the parameters 'name', 'email, 'password', not the '_id'
}

Your createUser function should have the following signature:

function createUser(OBJECT,CALLBACK_FUNCTION)

In this context, the callback function means it will only be executed when needed. You have to call that function explicitly as shown below:

function (err, user) { console.log(user); // Return only the params 'name', 'email, 'password', not the '_id' }

You are not handling promises here; instead, you are invoking a function with a callback parameter. Make sure to structure the function as follows and call the callback appropriately:

  createUser(user, callback) {
  User.save(user, function(data) {
    $cookies.put('token', data.token);
    currentUser = User.get();
    callback(null,user);//passing null as first parameter since there's no error
  }, function(err) {
    Auth.logout();
    callback(err);
  })
},

I hope this explanation helps. If you still have any doubts, feel free to ask. Is it possible that you missed a closing bracket?

 Auth.createUser({
         name: this.user.name,
         email: this.user.email,
         password: this.user.password,
       }, function (err, user) {
         console.log(user); // Return only the params 'name', 'email, 'password', not the '_id' 
});

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

Using a combination of stringify, regular expressions, and parsing to manipulate objects

As I review code for a significant pull request from a new developer, I notice their unconventional approach to editing javascript objects. They utilize JSON.stringify(), followed by string.replace() on the resulting string to make updates to both keys a ...

How can a function be invoked in a child component from a parent component?

I am facing a challenge where I need to trigger the function showExtraBlogposts() in Blogpostreader.js upon clicking on a button rendered in Blog.js. Initially, I attempted to call it using onClick={Blogpostreader.showExtraBlogposts()} but it returned an ...

Troubining AJAX for Generating a New Template: Addressing Missing Template Error

I have been working on integrating AJAX into my to-do application, but I keep encountering a missing template error (Missing template items/create, application/create with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :bu ...

"Trouble with props: List items not showing up after refreshing the page

I am facing an issue with my "Event Selector" component where it is not displaying the list items as expected. The component is supposed to create a button for each item in the 'lists' passed via props. Strangely, the items do not show up upon re ...

When using querySelectorAll, I am provided with an array that includes only a single

After appending some div elements with the class "todo" to the parent div with the id "no_status", I encountered an issue. When I console.log the parent div, it shows all child elements with the class "todo". However, when I use querySelectorAll to log all ...

Tips for detecting the existence of scrollbar on a webpage and retrieving its coordinates

I am working on a web page where I need to dynamically retrieve the scroll coordinates of the page. If a page has multiple scrolls, I should be able to get the respective scroll coordinates for each. The functionality needs to adjust based on the specifi ...

Merge two jQuery functions for handling JSON data in the best possible manner

I am new to jQuery and I have a question about combining two functions. The first function loads JSON data to trigger a click event. The second function toggles the view for list items. Can someone please help me and show me the correct way to combine t ...

The issue of Safari causing duplicate ajax calls to be submitted

Upon observation, it appears that Safari 5.0.5 (6533.21.1) is sending duplicate ajax calls. To illustrate this issue, I have conducted a simplified test as shown below: // jquery 1.6 include $(document).ready(function() { setTimeout(function(e) { ...

Concerns arise with jQuery grid compatibility in Firefox browsers

I have found an interesting tutorial on draggable image boxes grid at this link. Although everything is functioning properly, I am encountering an issue with the drag function specifically on the home page when using Firefox. As a beginner in jQuery, I am ...

The page switch with a jittery effect

Could really use some assistance with this code that has been giving me trouble for quite a while now. It's a simple HTML, CSS, and JS code involving two pages. [The second page overlaps the first by default, but adjusting the z-index of the first p ...

Firebase Authentication error code "auth/invalid-email" occurs when the email address provided is not in a valid format, triggering the message "The email address is

Currently, I am working on integrating Firebase login and registration functionality into my Angular and Ionic 4 application. Registration of user accounts and password retrieval are functioning properly as I can see the accounts in my Firebase console. Ho ...

What is the best way to update office-js dependencies in a React Outlook web add-in while ensuring safety?

I have a react outlook addin and I'm trying to figure out how to update it to the latest office-js-dependencies. The documentation seems confusing to me. It looks like I need to update the versions in my package.json file, but there isn't any cl ...

JavaScript: capturing all elements triggering an event

Whenever I interact with the monitor of my virtual mobile phone (using Chrome emulation), the event touchmove is triggered. I've tested the following line of code and it works. This confirms that the element ".button" is affected by this event, but h ...

Sorting Columns in PrimeVue DataTable by Date and Time

I am using a PrimeVue DataTable () with the following structure: <DataTable :rows = "5" :value = "apiItems" > <Column v-for="data in columns" :field="data.field" :header="data.header&q ...

Issues arise with jQuery onclick event functionality when the DOM structure is altered

I'm struggling to grasp the concept of jQuery (v1.11) when it comes to events and how DOM interaction impacts those events. The scenario: I am creating a grid of inline-blocks with the class "letter" and listening for clicks: $('.letter).on(&a ...

issues with the functionality of bootstrap modal

I'm currently working on a project where I need to set up a modal popup using bootstrap. The website I'm working on is organized by departments, so the only part of the code that I have control over is the main body of the site. I have included t ...

Javascript's ability to import and export modules is a powerful feature

It's clear that there is a strong interest in breaking down large JavaScript projects into smaller modules for code reuse, as discussed in this question. Research indicates that the import/export feature was specifically designed for this purpose and ...

Creating PDFs with barcodes using Node.js

Currently, I am utilizing https://github.com/devongovett/pdfkit to create PDF files easily. This can be achieved with a simple code snippet like below: app.get('/get-pdf', (req, res) => { const doc = new PDFDocument(); const filename = &ap ...

Is there a way to transform my button into a pop-up field displaying the same information instead of leading to a separate page?

Recently, I incorporated a highscore page with code that manages and updates the score, along with adding the username to a separate page. My goal is to have the HighScore button trigger a pop-up window when clicked, instead of navigating to another page. ...

The Data from Req.Body Doesn't Appear After Adding Form Fields

I've been struggling to find a solution to this issue, but here's the gist of it: I have a button that allows users to add a question and answer pair one at a time by clicking on an "Add Question" button. This is achieved through the append featu ...