Looking to establish a distinct member pathway

Imagine a scenario where I provide a list of 20 members with their names and phone numbers in a listing that also includes other attributes like title and price. The goal is to automatically check if these members already exist in the member list. If they do, return the price of the listing; if not, add the member to the member list. I am facing challenges in defining a specific schema for the member model—whether it should be an array, string, or key-value pair for the member's name and phone number. Even if I define a schema, retrieving it from the database for comparison purposes proves difficult. Essentially, what I need is a member list format such as member1, member2, etc. When creating the listing, these members should be compared with existing members to determine if they should return the price or create a new member entry with the provided name and phone number.

Listing Model

    const listingSchema = new Schema({
    title: { type: String },
    price: { type: Number },
    startDate: {
      type: Date,
    },
    currentMonth: { type: Number },
    endDate: {
      type: Date,
    },

    member: { type: String },
    phone: { type: Number },
    });

Member Model

    const memberSchema = new Schema({
      member: "String",
      phone: "Number",
    });

Listing Controller

    const newListing = new listing({
      title: req.body.title,
      price: req.body.price,
      startDate: req.body.startDate,
      currentMonth: req.body.currentMonth,
      endDate: req.body.endDate,
    member: req.body.member,
    });

    let member = newListing.member;
    // console.log(member);
    let present = await members.findOne([member]);
    console.log(present);

    member.forEach(async (e) => {
      // console.log(e);
      let existingMember = await members.findOne({ name: e });
      if (existingMember) {
        console.log("yes");
        console.log(req.body.price)
      } else {
        console.log("no");
        //createmember;
      }
    });

Member Controller

    try {
    const newMember = new member({
      member: [{ name: req.body.name, phone: req.body.phone }],
    });
    console.log(newMember);
    // let savedMember = await newMember.save();
    // console.log(savedMember);
    return res.json({ message: "New Members Created!" });
    } catch (error) {
    console.log(error);
    res.status(404).json(error, "cannot create new member");
    }

Answer №1

It seems like your goal is to retrieve the price of a listing that includes a specific member from the database, or create a new member if necessary.

1. Enhance your Member model

const memberSchema = new Schema({
  name: { type: String, required: true },
  phone: { type: Number, required: true, unique: true },  // ensure uniqueness of phone numbers
});

2. Upgrade your Listing model

const listingSchema = new Schema({
  title: { type: String },
  price: { type: Number },
  startDate: { type: Date },
  currentMonth: { type: Number },
  endDate: { type: Date },
  members: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Member' }]  // Array of Member references
});

Note: Consider creating a separate model and schema for storing members if your listings have a large number of members exceeding MongoDB's limit.

const membersOfListingSchema = new Schema({
  listing: { type: mongoose.Schema.Types.ObjectId, ref: 'Listing' },
  member: { type: mongoose.Schema.Types.ObjectId, ref: 'Member'}
});

This approach allows you to add multiple members to each listing without constraints.

3. Handling Member Creation or Retrieval

If you provide a set of members with names and phone numbers in your request body, consider the following code snippet for creating a new listing:

const createListing = async (req, res) => {
  try {
    const { title, price, startDate, currentMonth, endDate, members } = req.body;
    
    let memberIds = [];  
    
    for (const memberData of members) {
      let existingMember = await Member.findOne({ name: memberData.name, phone: memberData.phone });

      if (!existingMember) {
        const newMember = new Member({ name: memberData.name, phone: memberData.phone });
        existingMember = await newMember.save();
      }

      memberIds.push(existingMember._id);
    }

    const newListing = new Listing({
      title,
      price,
      startDate,
      currentMonth,
      endDate,
      members: memberIds 
    });

    const savedListing = await newListing.save();
    res.status(201).json(savedListing);

  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Failed to create listing' });
  }
};

Duplicates are automatically handled by MongoDB due to the unique constraint on the phone field in the memberSchema.

4. Retrieve Listings with Member Information

Utilize .populate() method for this purpose.

const listing = await Listing.findById(/*listing id*/).populate('members');

I hope this guide assists you in achieving your objectives effectively.

Answer №2

To begin with, it is important to store the name and number as individual records within the member model.

const memberInfoSchema = new Schema({
  fullName: { type: String, required: true, unique: true },
  phoneNumber: { type: Number, required: true, unique: true }
});

The schema for listings can then reference these members using the ObjectId. This establishes the connection between a listing and a member.

const listingInfoSchema = new Schema({
  productName: { type: String },
  cost: { type: Number },
  start: { type: Date },
  currentPeriod: { type: Number },
  end: { type: Date },
  membersList: [{ type: Schema.Types.ObjectId, ref: 'Member' }]
});

In order to manage existing members and add new ones if necessary, you can follow this approach:

const saveOrUpdateListingData = async (req, res) => {
  try {
    const requestedMembers = req.body.members; // assuming req.body.members is an array of {fullName, phoneNumber}
    const memberIdArray = [];

    for (const info of requestedMembers) {
      let presentMember = await Member.findOne({ fullName: info.fullName, phoneNumber: info.phoneNumber });
      
      if (!presentMember) {
        const freshMember = new Member({
          fullName: info.fullName,
          phoneNumber: info.phoneNumber
        });
        presentMember = await freshMember.save();
      }

      memberIdArray.push(presentMember._id); 
    }

    const freshListing = new Listing({
      productName: req.body.productName,
      cost: req.body.cost,
      start: req.body.start,
      currentPeriod: req.body.currentPeriod,
      end: req.body.end,
      membersList: memberIdArray
    });

    const storedListing = await freshListing.save();
    res.status(201).json(storedListing);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'An error occurred while creating the listing' });
  }
};

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

Expanding the width of Material UI Javascript Dialog Box

Currently, I am utilizing the dialog feature from Material UI in my React JS project and I am looking to expand its width. After some research, I discovered that there is a property called maxWidth which allows you to adjust the width of the dialog. Howe ...

"The boundary of suspense was updated before completing hydration." This error occurs when utilizing suspense and dynamic import within Next.js

I am currently working on lazy loading a list of data using suspense and dynamic import in Nextjs. However, I encountered the following error: Error: This Suspense boundary received an update before it finished hydrating. This caused the boundary to switch ...

Determine a person's vertical measurement with jQuery

Is there a way to determine the distance from the top of the page to where a link has been inserted? For example, we can use the following code snippet to calculate the height of the window: w = $(window).height(); I am interested in finding out how to ...

Guidelines for utilizing React to select parameters in an Axios request

As a newcomer to ReactJs, I am working with a Product table on MySQL. I have successfully developed a dynamic table in the front-end using ReactJS along with MySQL and NodeJs on the backend. The dynamic table consists of four columns: Product, Quantity, Pr ...

Can the axios version be displayed during runtime?

I have incorporated axios into my project using npm import axios from 'axios' Is there a way to print the version of axios in the console after the entire application has been compiled? ...

cssclassName={ validatorState === RIGHT ? 'valid' : 'invalid' }

Is there a way to dynamically add different classes based on validation outcomes in React? My current implementation looks like this: className={ validatorState === RIGHT ? 'ok' : 'no' } However, I also need to handle cases where the ...

Is there a way to stop Bootstrap from automatically bolding the font?

When testing this simple example without the bootstrap link, everything seems to be working correctly: Hovering over any word changes its color to red, and when hovering away it returns to black. But as soon as the bootstrap link is included, the text bec ...

What purpose does Webpack serve in injecting React?

Within my webpack entry file, I have the following code snippet: import ReactDOM from 'react-dom'; import Layout from './components/Layout'; // ... dialog = document.createElement("dialog"); ReactDOM.render(<Layout dialog={dialog} ...

Concealing a button in Vue.js and Laravel effortlessly

I am struggling to figure out how to hide the button when there is no data in the table in my Vue.js project. Since I am new to Vue.js, I would really appreciate any help or guidance on how to achieve this. If there is another way to accomplish this, pleas ...

Error encountered: Attempting to use a class as a function in vue-socket.io is not permitted

I am developing a Vue chrome extension where I am attempting to implement web sockets using vue-socket.io. I have followed the basic instructions on deploying a node server with express and socket.io on Heroku, but I am encountering issues with the conne ...

What is the best library to utilize for uploading an Excel file in a React application?

As a beginner in JS and React, I have a simple question that I hope someone can help me with! I am trying to figure out how to upload an excel file using a form and then extract the data from the rows and columns. For example, I would like to calculate th ...

tagit: update the label's value

I've been utilizing the jquery ui plugin https://github.com/aehlke/tag-it to incorporate tagging functionality into my project. This is how I am creating tags: $("#Input").tagit("createTag", "ABC"); My goal is to append additional text to the labe ...

Removing specific data from the `user_data` array in Codeigniter session

There is an array called 'cart' stored inside my session. Here's how it looks: Array ( [session_id] => 4a5a5dca22728fb0a84364eeb405b601 [ip_address] => 127.0.0.1 [user_agent] => Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; [la ...

I find it impossible to avoid using the withRouter and withAlert functionalities in Reactjs

When using withRouter, the alert.success property is not accessible. A TypeError is thrown with the message "Cannot read property 'success' of undefined". This issue prevents the successful display of alerts in my application. The error occurred ...

Leveraging the power of ES6, achieve recursion with requestAnimationFrame in

Lately, I've been working on creating a versatile SceneManager class that not only manages scenes but also handles rendering. class SceneManager { constructor() { this.scene = new THREE.Scene(); this.camera = new THREE.Perspectiv ...

Refresh the React state at regular intervals

constructor(){ super(); this.state={ numbers : [1,2,3,4,1,2,3,4,1,3,1,4,12,2,3,2] }; } componentDidMount(){setInterval(this.updateNumbers(),5000);} updateNumbers() { console.log(this.props.newData); let numbers = this.state.nu ...

Clicking on the anchor at the bottom of the page will smoothly navigate you to the top of the page

I added an anchor at the bottom of the page. I wrapped a group of buttons with the link so that when clicked, they trigger the assigned JavaScript and scroll to the bottom of the page. However, the buttons currently execute the JavaScript but then take you ...

Creating custom elements for the header bar in Ionic can easily be accomplished by adding your own unique design elements to the header bar or

I'm a beginner with Ionic and I'm looking to customize the items on the header bar. It appears that the header bar is created by the framework within the ion-nav-bar element. <ion-nav-bar class="bar-positive"> <ion-nav-back-button> ...

Navigating with nodeJS

Currently, I am in the process of learning how to create a Node.js project. My latest endeavor involved following a tutorial to develop a chat application. However, it seems like there is an issue with the routing between the server side and client side. ...

Is it possible for the JTable constructor to accept data structures other than arrays?

public JTable(Object rowData[][], Object columnNames[]) Object rowData[][] = { { "Row1-Column1", "Row1-Column2", "Row1-Column3"}, { "Row2-Column1", "Row2-Column2", "Row2-Column3"} }; Object columnNames[] = { "Column One", "Column Two ...