I looked at this popular question, but it didn't seem to fix my issue, so I'm going to post this.
I currently have an express.js server file using mongoose, that keeps returning an empty array. I have no idea if it might by an async issue, and I don't know what I can use to indicate that I'm connected to my database.
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const PORT = process.env.PORT || 8080;
//Mongoose stuff
mongoose.connect('mongodb+srv://excelsiorAdmin:Mysecretpassword@excelsiorcluster-zakfd.mongodb.net/test?retryWrites=true', { useNewUrlParser: true, dbName: 'excelsiorDB'});
const dbConnection = mongoose.connection;
dbConnection.on('error', console.error.bind(console, 'connection error:'));
dbConnection.once('open', function() {
console.log('connected to the database');
let charSchema = new mongoose.Schema({
imageURL: String,
company: String,
name: String,
civName: String,
alignment: String,
firstDebut: String,
abilities: Array,
teams: Array,
desc: String
});
let Char = mongoose.model('Char', charSchema, 'chars');
//root
app.get('/', (req, res, next) => res.send('Welcome to the API!'));
//get all characters
app.get('/chars', (req, res, next) => {
console.log('getting all characters');
Char.find(function (err, chars) {
if (err) {
res.status(404).send(err);
console.log('there was an error');
};
console.log(chars);
res.send(chars);
});
});
//get heroes
app.get('/chars/heroes', (req, res, next) => {
Char.find({alignment: "Hero"}, function (err, chars) {
if (err) {
res.status(404).send(err);
};
res.send(chars);
});
});
});
app.listen(PORT, () => console.log(`This API is listening on port ${PORT}!`));