How to connect different MongoDB collections to React

Please help me out with this as I can’t find the answer anywhere.

My MongoDB Database name is myWebsiteDB:

  • myWebsiteDB has 2 collections: dinners and emails.
  • I have connected dinners collection to use in my website as a CRUD app – works fine.
  • Now I want to save data from Email Subscription section’s input field to the emails collection on my website.
  • These 2 collections are for saving 2 different data intentions, so I don’t want to join them.

I tried setting up the emails collection Schema and connecting it to my React App exactly like the way I connected the dinners collection before, here are the challenges that I’m facing:

  1. When I click the Submit Email button, it doesn’t work and the errors returned from the server’s terminal seem like it’s the validation for the dinners collection, not the emails collection that I
    m trying to write in. See screenshot

  2. Am I using validator and writing the new Emails schema right? Do I need to specify the {collection: collection name} like below?

Here are my code:

Emails Model (Emails.js):

const mongoose = require('mongoose')
const validator = require('validator')

const EmailSchema = new mongoose.Schema({
    email: {
        type: String,
        trim: true,
        lowercase: true,
        unique: true,
        validate: {
            validator: validator.isEmail,
            message: 'Please input a valid email address',
            isAsync: false
        }
    }
}, {collection: "emails"})

const Emails = mongoose.model('Emails', EmailSchema)
module.exports = Emails

Dinner Model (Dinner.js):

const mongoose = require('mongoose')

const DinnerSchema = new mongoose.Schema({
    foodName: {
        type: String,
        required: true,
    },
    isVegetarian: {
        type: Boolean,
        required: true,
    },
    priceRange: {
        type: String,
        required: true,
    }
}, {collection: "dinners"})

const Dinner = mongoose.model("Dinner", DinnerSchema)
module.exports = Dinner

Server side index.js:

const express = require("express") // Set up an express server
const mongoose = require("mongoose") // Import Mongoose library
const cors = require('cors') // Import CORS to communicate with frontend
const app = express() // Initializing our express server

const DinnerModel = require('./models/Dinner')
const EmailModel = require('./models/Emails')

app.use(express.json()) // Setting up Middleware
app.use(cors())

// Connect to MongoDB
mongoose.connect(
    'mongodb+srv://myusername:[email protected]/myWebsiteDB?retryWrites=true&w=majority', 
    {
        useNewUrlParser: true,
    }
)

// Create:
app.post("/insert", async (req, res) => {
    const foodName = req.body.foodName
    const isVegetarian = req.body.isVegetarian
    const priceRange = req.body.priceRange
    const email = req.body.email

    // Dinner Ideas App:
    const dinner = new DinnerModel(
        { 
            foodName: foodName, 
            isVegetarian: isVegetarian,
            priceRange: priceRange,
        }
    )

    // Email:
    const emailData = new EmailModel(
        {
            email: email
        }
    )

    try {
        await dinner.save()
        await emailData.save()
        res.send("data inserted")
        
    } catch(err) {
        console.log(err)
    }
})

// Read:
app.get("/read", async (req, res) => {
    DinnerModel.find({}, (err, result) => {
        if (err) {
            res.send(err)
        }
        res.send(result)
    })
})

// Update:
app.put("/update", async (req, res) => {
    const newFoodName = req.body.newFoodName
    const id = req.body.id

    try {
        await DinnerModel.findById(id, (err, updatedFood) => {
            updatedFood.foodName = newFoodName
            updatedFood.save()
            res.send("update")
        }).clone()
    } catch(err) {
        console.log("The error is: " + err)
    }
})


app.delete("/delete/:id", async (req, res) => {
    const id = req.params.id

    await DinnerModel.findByIdAndRemove(id).exec()
    res.send("deleted")
})

// Creating a port:
app.listen(3001, () => {
    console.log("Server is up on: http://localhost:3001")
})

React code with CRUD using the dinners collection:

import React, { useState, useEffect } from "react"
import './DinnerIdeas.css'
import Axios from "axios"
import FoodListComponent from "../FoodListComponent";
import FormComponent from "../FormComponent";


function DinnerIdeas() {

    const [foodName, setFoodName] = useState('')
    const [isVegetarian, setVegetarian] = useState(false)
    const [priceRange, setPriceRange] = useState('$')
    const [newFoodName, setNewFoodName] = useState('')
    const [foodList, setFoodList] = useState([])
  
    // Read:
    useEffect(() => {
      let unmounted = false
      Axios.get("http://localhost:3001/read")
      .then((response) => {
        if (!unmounted) {
          setFoodList(response.data)
        }
      })
      .catch(error => {
        console.log(`Hey, the error is ${error}`)
        return
      })
      return () => {
        unmounted = true
      }
    }, [foodList])
  
    // Create:
    const addToList = () => {
      Axios.post(
        "http://localhost:3001/insert", 
        {
          foodName: foodName,
          isVegetarian: isVegetarian,
          priceRange: priceRange,
        }
      )
    }
  
    // Update:
    const updateFood = (id) => {
      if (newFoodName) {
        Axios.put("http://localhost:3001/update", {
          id: id,
          newFoodName: newFoodName,
        })
        .catch(error => console.log(`Hey, the error is ${error}`))
      }
    }
  
    // Delete:
    const deleteFood = (id) => {
      Axios.delete(`http://localhost:3001/delete/${id}`)
    }
    
    return (
      <section className="dinner-ideas">
        <FormComponent
          setFoodName={setFoodName}
          setVegetarian={setVegetarian}
          setPriceRange={setPriceRange}
          addToList={addToList}
        />
        <FoodListComponent 
          foodList={foodList} 
          setNewFoodName={setNewFoodName}
          updateFood={updateFood} 
          deleteFood={deleteFood}
          newFoodName={newFoodName}
        />
      </section>
    );
  }
  
  export default DinnerIdeas;

React Footer Component that let users put in their emails to subscribe, this will write to the emails collection:

import React, { useState } from "react"
import Axios from "axios"



export default function FooterComponent() {

    const [email, setEmail] = useState('')

    const subscribeEmail = () => {
        Axios.post(
            "http://localhost:3001/insert",
            {
                email: email
            }
        )
    }


    return (
        <footer>
            <div>Created by higherstates &copy; 2021</div>
            <div>
                <h3>Interested in further deals?</h3>
                <input
                    type='email'
                    placeholder="Give us your email"
                    onChange={(event) => {setEmail(event.target.value)}}
                />
                <button 
                    type="submit"
                    onClick={subscribeEmail}
                >
                    Submit Email
                </button>
            </div>
        </footer>
    )
}

Please guide me on how to fix this, thank you! 🙂