title: Connecting to multiple collections in MongoDB
body: <p>I am trying to access two collections of my MongoDB for my React app. I have constructed two API_URLs:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const API_URL = window.location.hostname === 'localhost' ? 'http://localhost:5000/api/v1/Sessions' : 'production-url-here'
  
  const API_URL1 = window.location.hostname === 'localhost' ? 'http://localhost:5000/api/v1/members' : 'production-url-here'</code></pre>
  </div>
  </div>
  </p>
  
  <p>The sessions collection is returned with raw data when I put the url into my browser but the members URL returns a "not found" message. </p>
  
  <p>I have mirrored my server and client side code of the sessions collection for my members collection and Im unsure as to what the issue is. </p>
  
  <p>Here is the code for members.js:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const express = require('express');
  const Joi = require("joi");
  
  const db = require('../db');
  const members = db.get('members');
  
  //Defining the schema for the backend.
  const schema1 = Joi.object().keys({
      name:   Joi.string().min(1).max(100).required(),
      bio:   Joi.string().min(1).max(500).required(),
      latitude:    Joi.number().required(),
      longitude:   Joi.number().required()
  });
  
  const router = express.Router();
  
  //Gets all sessions that are found within the DB.
  router.get('/', (req, res) =&gt; {
    members
    .find()
    .then(allmembers =&gt;{
        res.json(allmembers);
      });
  });
  
  module.exports = router;</code></pre>
  </div>
  </div>
  </p>
  
  <p>Here is the code for Sessions.js : </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const express = require('express');
  const Joi = require("joi");
  
  const db = require('../db');
  const Sessions = db.get('Sessions');
  
  //Defining the schema for the backend.
  const schema = Joi.object().keys({
      event:   Joi.string().min(1).max(100).required(),
      venue:   Joi.string().min(1).max(500).required(),
      address: Joi.string().min(1).max(100).required(),
      dtstart: Joi.string().required(),
      dtend:   Joi.string().required(),
      latitude:    Joi.number().required(),
      longitude:   Joi.number().required()
  });
  
  const router = express.Router();
  
  //Gets all sessions that are found within the DB.
  router.get('/', (req, res) =&gt; {
    Sessions
    .find()
    .then(allSessions =&gt;{
        res.json(allSessions);
      });
  });
  //POST for when no errors are produced.
  router.post('/', (req, res, next) =&gt; {
    const result = Joi.validate(req.body, schema);
    if (result.error == null) {
  //Removes the need to write eg) req.body.name below.
      const { event, venue, address, latitude, longitude, dtstart, dtend,} = req.body;
      const Session = {
        event,
        venue,
        address,
        dtstart,
        dtend,
        latitude,
        longitude,
        date: new Date()
       };
     Sessions.insert(Session).then(insertedMessage =&gt; {
           res.json(insertedMessage);
     });
   }
  else {
    next(result.error);
     }
  });
  
  module.exports = router;</code></pre>
  </div>
  </div>
  </p>
  
  <p>Frontend code: </p>
  
  <pre class="lang-react prettyprint-override"><code>import React, { Component } from 'react';
  import './App.css';
  import L from 'leaflet';
  import Joi from 'joi';
  //import only modules needed or error.
  import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
  import { Card, CardTitle, CardText } from 'reactstrap';
  import {Form, FormGroup, Label, Input } from 'reactstrap';
  import { Button } from 'reactstrap';
  import Chart from './components/Chart';
  
  
  var myIcon = L.icon({
      iconUrl: 'https://purepng.com/public/uploads/large/purepng.com-harpharpstringedsoundboardfingersmodern-1421526538276nepuu.png',
      iconSize: [25, 51],
      iconAnchor: [12.5, 51],
      popupAnchor: [0, -51],
      draggable: true,
  });
  //Joi creates the schema for validation
  const schema = Joi.object().keys({
      event: Joi.string().min(1).max(100).required(),
      venue: Joi.string().min(1).max(500).required(),
      address: Joi.string().min(1).max(100).required(),
      dtstart: Joi.string().required(),
      dtend:   Joi.string().required()
  });
  
  const schema1 = Joi.object().keys({
      name:   Joi.string().min(1).max(100).required(),
      bio:   Joi.string().min(1).max(500).required(),
      latitude:    Joi.number().required(),
      longitude:   Joi.number().required()
  });
  
  //URL declaration, if hostname is localhost, request backend. otherwise URL.
  const API_URL = window.location.hostname === 'localhost' ? 'http://localhost:5000/api/v1/Sessions' : 'production-url-here'
  const API_URL1 = window.location.hostname === 'localhost' ? 'http://localhost:5000/api/v1/members' : 'production-url-here'
  
  class App extends Component {
    state = {
      location: {
          lat: 51.505,
          lng: -0.09,
   },
   UserslocationFound: false,
     zoom: 12,
     /* Monitors the state of the users inputs (detects changes). */
     UsersSession: {
       event: '',
       venue: '',
       address: '',
       dtstart: '',
       dtend: ''
     },
     Sessions: [],
     members: []
   }
  componentDidMount() {
    //Grabs the markers from the Thesession API to be displayed.
    fetch(API_URL)
       .then(res =&gt; res.json())
       .then(Sessions =&gt; {
         this.setState({
           Sessions
         });
       });
  
       fetch(API_URL1)
          .then(res =&gt; res.json())
          .then(members =&gt; {
            this.setState({
              members
            });
          });
  
    /*Asks user for location via google alert. */
    navigator.geolocation.getCurrentPosition((position) =&gt; {
      this.setState({
        location: {
          lat:  position.coords.latitude,
          lng: position.coords.longitude
        },
        UserslocationFound: true,
        zoom: 15,
        draggable: true
      });
    }, () =&gt; {
      console.log("Location not given ");
      fetch('https://ipapi.co/json')
        .then(res =&gt; res.json())
        .then(location =&gt; {
            console.log(location);
            this.setState({
              location: {
                lat:  location.latitude,
                lng: location.longitude
              },
              UserslocationFound: true,
              zoom: 15
            });
        });
  });
  }
  
  formSubmitted = (event) =&gt; {
  /* prevents the page from refreshing on submit. */
    event.preventDefault();
    console.log(this.state.UsersSession);
    const UsersSession = {
      event: this.state.UsersSession.event,
      venue: this.state.UsersSession.venue,
      address: this.state.UsersSession.address,
      dtstart: this.state.UsersSession.dtstart,
      dtend: this.state.UsersSession.dtend
    };
    //importing Joi to get the result through validation of the inputs with the schema.
    const result = Joi.validate(UsersSession, schema);
    if(!result.error) {
  //fetching against API_URL
      fetch(API_URL, {
        method: 'POST',
        headers: {
          'content-type': 'application/json',
  
        },
        body: JSON.stringify({
          ...UsersSession,
          latitude: this.state.location.lat,
          longitude: this.state.location.lng,
        })
      }).then(res =&gt; res.json())
      .then(Sessions =&gt; {
        console.log(Sessions)
      });
    }
  }
  
  /*Updates the state on UsersSession */
  valueChanged = (event) =&gt; {
    /*declaring event.target as it throws errors in chrome */
    const { name,value } = event.target;
    /*Sets usersSession to be the value defined in inputs */
     this.setState((prevState) =&gt; ({
       UsersSession: {
         ...prevState.UsersSession,
         [name]: value
       }
     }))
  }
  //Sharing of code between React components
    render() {
       const position = [this.state.location.lat, this.state.location.lng]
      return (
        &lt;div className ="map"&gt;
        &lt;Map className ="map" center={position} zoom={this.state.zoom}&gt;
        /* tile imported to use over leafletjs*/
           &lt;TileLayer
             attribution='&amp;amp;copy &lt;a href="http://osm.org/copyright"&gt;OpenStreetMap&lt;/a&gt; contributors'
             url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
           /&gt;
  
           /* displays marker for when users location is given/found */
           { this.state.UserslocationFound ?
  
           &lt;Marker
                  position={position}
                  icon={myIcon}&gt;
           &lt;/Marker&gt; : ''
  
           }
           {this.state.Sessions.map(UsersSession =&gt; (
             &lt;Marker
                     position={[UsersSession.latitude, UsersSession.longitude]}
                     icon={myIcon} &gt;
                &lt;Popup&gt;
                &lt;em&gt;{UsersSession.event}, &lt;/em&gt;
                    {UsersSession.venue} {'\n'}
  
                    &lt;Button color="primary" size="sm"&gt;More info&lt;/Button&gt;
                    &lt;Chart/&gt;
                &lt;/Popup&gt;
             &lt;/Marker&gt;
           ))}
  
           {this.state.members.map(Users =&gt; (
             &lt;Marker
                     position={[Users.latitude, Users.longitude]}
                     icon={myIcon} &gt;
                &lt;Popup&gt;
                &lt;em&gt;{Users.name}, &lt;/em&gt;
                    {Users.bio} {'\n'}
  
                    &lt;Button color="primary" size="sm"&gt;More info&lt;/Button&gt;
                    &lt;Chart/&gt;
                &lt;/Popup&gt;
             &lt;/Marker&gt;
           ))}
         &lt;/Map&gt;
         &lt;Card body className="message-form"&gt;
          &lt;CardTitle&gt;Welcome to TradMap!&lt;/CardTitle&gt;
          &lt;CardText&gt;Please input the details of your Session below.&lt;/CardText&gt;
          &lt;Form onSubmit={this.formSubmitted}&gt;
         &lt;FormGroup&gt;
           &lt;Label for="name"&gt;Session Title&lt;/Label&gt;
           &lt;Input
           /*when the state changes */
             onChange={this.valueChanged}
             type="text"
             name="event"
             id="event"
             placeholder="..." /&gt;
  
             &lt;Label for="startDate"&gt;Start Date&lt;/Label&gt;
             &lt;Input
               onChange={this.valueChanged}
               type="date"
               name="dtstart"
               id="dtstart" /&gt;
  
            &lt;Label for="EndDate"&gt; End Date &lt;/Label&gt;
               &lt;Input
                 onChange={this.valueChanged}
                 type="date"
                 name="dtend"
                 id="dtend" /&gt;
  
                 &lt;Label for="venue"&gt;Session Venue&lt;/Label&gt;
                 &lt;Input
                   onChange={this.valueChanged}
                   type="textarea"
                   name="venue"
                   id="venue"
                   placeholder="..." /&gt;
  
                 &lt;Label for="Address"&gt;Session Address&lt;/Label&gt;
                 &lt;Input
                   onChange={this.valueChanged}
                   type="textarea"
                   name="address"
                   id="address"
                   placeholder="..." /&gt;
        &lt;/FormGroup&gt;
  
         &lt;Button type ="submit" color="info" disabled={!this.state.UserslocationFound}&gt;submit&lt;/Button&gt;
         &lt;/Form&gt;
        &lt;/Card&gt;
        &lt;/div&gt;
      );
    }
  }
  
  export default App;
  </code></pre>