Ways to store extra user information in meteor.js beyond just the basic details, like their home address

Just starting out with Meteor.js, I decided to try my hand at creating a task list by following the tutorial on meteor.com. Adding the accounts-ui and accounts-password packages was a breeze, but now I'm looking to customize the sign-up process. In addition to basic user credentials, I also want to collect home address information and potentially more data. My goal is to store this additional info in mongodb, linked to each user's ID. Any suggestions on how I can achieve this?

Answer №1

To store additional information about the user, you can utilize the profile field in their profile.

Here's an example of how to do this on the client side when handling events:

Template.example.events({
 'click #register':function(event,template){
   var homeAddress = template.$('homeAddress').val();
     Accounts.createUser({
       email: email,
      password: password,
      profile: { homeAddress: homeAddress }
    });
 }
})

Keep in mind that fields like username, email, and profile are already included by default in the accounts-password package.

Answer №2

If you're in search of the additional option for a profile when utilizing Accounts.createUser(), make sure to refer to the documentation for detailed instructions on how to implement it: .

The profile feature requires an object that will be added to the database document linked with the user. Once you've tested the example below, execute the following commands to confirm that it has been stored in the database.

Within your project directory:
$ meteor mongo
$ db.users.find()

A sample output might look like this:

{ "_id" : "kJNaCtS2vW5qufwJs", "createdAt" : ISODate("2015-05-11T20:50:21.484Z"), "services" : { "password" : { "bcrypt" : "$2a$10$LrcZ5lEOlriqvkG5pJsbnOrfLN1ZSCNLmX6NP4ri9e5Qnk6mRHYhm" }, "resume" : { "loginTokens" : [ { "when" : ISODate("2015-05-11T20:50:21.493Z"), "hashedToken" : "CXKwUhEkIXgdz61cHl7ENnHfvdLwe4f0Z9BkF83BALM=" } ] } }, "emails" : [ { "address" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfccd7decdd4ddc6cbdaffccd0d2dadad2ded6d391dcd0d2">[email protected]</a>", "verified" : false } ], "profile" : { "firstName" : "shark", "lastName" : "byte" } }

Please note that I am not using accounts-ui, only accounts-password without the built-in UI. However, here's a guide on creating a basic account creation template with extra fields (such as first & last name, and organization).

HTML code:

<head>
  <title>test</title>
</head>

<body>
  <!-- checks if someone is logged in -->
  {{#if currentUser}}
    {{> userPage}}
  {{else}}
    {{> loginPage}}
  {{/if}}
</body>

<template name="userPage">
  <button id="logout">logout</button>
  <p>You are logged in!</p>
</template>

<template name="loginPage">
  <form><!-- create account form, use a different one for normal logging in -->
    <input type="text" id="firstName" placeholder="First Name">
    <input type="text" id="lastName" placeholder="Last Name">
    <input type="text" id="organization" placeholder="Organization (optional)">
    <input type="text" id="email" placeholder="Email Address">
    <input type="password" id="password" placeholder="Password">
    <input type="password" id="confirmPassword" placeholder="Confirm Password">
    <input type="submit" id="createAccount" value="Create Account">
  </form>
</template>

Javascript code:

if (Meteor.isClient) {
  Template.loginPage.events({
    'submit form': function(event, template) {
        event.preventDefault();
        console.log('creating account');
        var passwordVar = template.find('#password').value;
        var confirmVar = template.find('#confirmPassword').value;
        if (passwordVar === confirmVar) {
            Accounts.createUser({
                email: template.find('#email').value,
                password: passwordVar,
                // you can add wherever fields you want to profile
                // you should run some validation on values first though
                profile: {
                  firstName: template.find('#firstName').value,
                  lastName: template.find('#lastName').value
                }
            });
        }
    }
  });
  // ensure there is a logout button
  Template.userPage.events({
    'click #logout': function(event, template) {
      Meteor.logout();
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

Answer №3

One way to enhance user creation on the server side is by utilizing the Accounts.onCreateUser hook.

if (Meteor.isServer) {
    Meteor.startup(function() {
    });

    Accounts.onCreateUser(function(options, user) {
        if (options.profile) {
            user.profile = options.profile;
        }

        user.profile.address = 
        user.profile.city = 
        user.profile.state = 
        user.profile.zip =
        user.profile.anything = 
    return user;
});

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

Evaluate a program to identify prime numbers

I am currently working on a JavaScript program that utilizes recursion to determine whether an input is a prime number or not. Within my code, I've defined the isPrime function. The base cases are set to return false when x==1 and true for x==2, cons ...

Invoking a function containing an await statement does not pause the execution flow until the corresponding promise is fulfilled

Imagine a situation like this: function process1(): Promise<string> { return new Promise((resolve, reject) => { // do something const response = true; setTimeout(() => { if (response) { resolve("success"); ...

Choosing age quantity without any breaks

My goal is to create a query that provides a count of people at each age, rather than in increments. I understand little about NoSQL, but I know that age counts must be updated regularly due to the ongoing passage of time. My idea involves utilizing a coll ...

A different approach to joining strings

Is there a different method to combine a '#' symbol like in the code snippet below? radioButtonID = '#' + radioButtonID; ...

Utilize a class method within the .map function in ReactJS

In my ReactJS file below: import React, { Component } from "react"; import Topic from "./Topic"; import $ from "jquery"; import { library } from '@fortawesome/fontawesome-svg-core' import { FontAwesomeIcon } from '@fortawesome/react-fontaw ...

Creating a key-value pair array upon checking a checkbox with jQuery

Every time I check a checkbox, two key-value pairs are generated, such as: Object {id: "101", name: "example"} These pairs are generated for each checked checkbox, and I want to create an array with multiple checkbox values that look like this: [{id:" ...

I'm looking for the best way to send POST data to an API with Meteor's HTTP package

Here's my current code snippet: HTTP.post("http://httpbin.org/post", {}, function(error, results) { if (results) { console.log(results); } else { console.log(error) } ...

Modifying property values using the onError event when encountering an error with the MUI DateTimePicker and

My goal is to set the 'myError' variable to true when MUI DateTimePicker throws an onError event, but for some reason it's not working. The code itself seems correct because if I replace () => {setValue({ ...value, ...

Discovering the method to modify the value of one input text field according to a particular value in another input text field

This is my HTML Code: <div class="modal-body"> <form action="edit.jsp" method="post"> <div class="form-group"> <label>Order ID</label> <input type="text ...

Retrieve a JSON object from a Knockout observable array using the object's ID

I'm struggling to find examples of ko.observablearrays that deal with complex JSON objects instead of simple strings. I have an observable array containing a large JSON object with several properties, and I need to retrieve a specific object based on ...

Ways to remove an item from firebase database

Currently, I am exploring ways to delete data stored in the Firebase database specifically under the requests category. Check out this example Below are the functions I have implemented to fetch and manipulate the data: export default { async contactArtis ...

Understanding how to utilize the scoped slot prop within a parent computed property

Currently, I have a closely connected pair of parent-child components utilizing a scoped slot. The child component sends data to the parent through a scoped slot prop (which we'll refer to as myScopedProp). Everything is functioning smoothly in this s ...

Trouble with Swiper carousel loading new slides

Currently, I am working on a project using Cordova and jQuery. I have implemented the Swiper library by idangero for handling slides. The problem arises when I add new slides and try to display them. Here is the relevant jQuery code snippet: if(row.pict ...

Populating MongoDB based on a specific condition

Currently, I have a set of collections where I am attempting to convert a log object into its detailed information by using the populate method. Companies (each company with its corresponding users): [ { _id: "comp123", compa ...

What is the process of retrieving a dynamic array value based on checkbox selection in AngularJS?

I need help with a situation where I am trying to use Angular to get the value of a checkbox. I have a Java object on my HTML page and when a user checks an individual box, that single value should be added to my array. If the user checks 'Select All& ...

Is it necessary to execute Commit and Begintransaction in SELECT queries?

I'm an MySQL beginner. Should we use commit or beginTransaction in SELECT statements? Let's say the query looks like this db.query("SELECT * FROM my_table") In this scenario, do we need to use commit or beginTransaction? db.query(&quo ...

Optimizing database choices to enhance performance and scalability of C# APIs

I am currently working on the development of a dating app, similar to Tinder or Bumble. As I embark on this project, I find myself faced with a decision between using Cassandra or MongoDB as the database. While my prior experience lies in MS SQL, mysql and ...

The error message "Error [ERR_HTTP_HEADERS_SENT]: Unable to set headers after they have been sent to the client" indicates that

Continuously encountering an error related to a res.redirect despite adding a 'return' in the function to end the middleware. The error persists despite attempting to resolve it in this manner. Below is the function in question: app.post('/ ...

Reset input value when adding or removing inputs dynamically

Currently, I have an input element that has the capability to clear its value when a button is clicked. Additionally, this input can dynamically add or remove input elements. However, I am facing an issue where after adding an input element, the clear butt ...

Child object referencing in JavaScript

As I delved into testing Javascript, a curiosity arose regarding the interaction between child and parent objects. Would the parent object dynamically update to reflect changes in the child object's value, or would it remain static at the initial stat ...