1

I'm trying to query the data in my MongoDB database from my app using the Mongoose module, and what's being returned is an empty array.

The most common answer in SO is that Mongoose pluralizes the collection name when creating the model. However, I believe I have no problem there (if actually I'm doing this wrong, please explain it to me).

At this point, all I've tried doing is selecting all of the entries using Result.find({}, callback), but again, just an empty array is returned.

When I query the data on the command line, I get the expected result. Below I just retrieved one entry for brevity.

Mongo shell on command line:

> db.getName()
kaplanFfl
> db.getCollection('results')
kaplanFfl.results
> db.results.findOne({ Owner: 'Sample'})
{
        "_id" : ObjectId("5a24c90b46521500830aa042"),
        "Owner" : "Sample",
        "Pts" : 81.5,
        "Week" : 1,
        "SeasonAvg" : 86,
        "Lst8_Avg" : 92,
        "Lst4_Avg" : 91,
        "Mean" : 82,
        "High" : 116,
        "Low" : 55,
        "Diff" : 61,
        "Dev" : 16.49141822,
        "Elite" : 0,
        "Superior" : 0,
        "Inferior" : 0,
        "Abyssmal" : 0,
        "MeanPlus" : 0,
        "MeanMinus" : -1
}

Here's the code:

model.js

'use strict';

const mongoose = require('mongoose');
let Schema = mongoose.Schema;

let resultSchema = new Schema({
    Owner: String,
    Pts: Number,
    Week: Number,
    SeasonAvg: Number,
    Lst8_Avg: Number,
    Lst4_Avg: Number,
    Mean: Number,
    High: Number,
    Low: Number,
    Diff: Number,
    Dev: Number,
    Elite: Number,
    Superior: Number,
    Inferior:Number,
    Abyssmal: Number,
    MeanPlus: Number,
    MeanMinus: Number
})

let WeeklyResult = mongoose.model('result', resultSchema);

module.exports = WeeklyResult;

index.js

const express = require('express');
const app = express();

const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const Result = require('./models/models');

const PORT = process.env.PORT || 3000;

//username and password has been removed, but it does connect
const uri = 'mongodb://<username>:<password>@kaplanffl-shard-00-00-rmbku.mongodb.net:27017,kaplanffl-shard-00-01-rmbku.mongodb.net:27017,kaplanffl-shard-00-02-rmbku.mongodb.net:27017/kaplanFfl?ssl=true&replicaSet=kaplanFfl-shard-0&authSource=admin'


//open the connection to the database
mongoose.Promise = global.Promise;

mongoose.connect(uri, {
    useMongoClient: true
})

let db = mongoose.connection;

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

db.on('error', console.error.bind(console, 'Connection error: '));
db.once('open', function() {

    console.log('Connection to MongoDB is live. Database: ' + db.name);
    Result.find({}, function(err, results) {
        if (err) console.log(err);
        console.log(results);
    })
})


//start web server
app.listen(PORT, (req, res) => {
    console.log('Server live on port ' + PORT);
});

I expect to get all of the results, but only get the following in the console:

Server live on port 3000
Connection to MongoDB is live. Database: kaplanFfl
[]

So, I feel as though the pluralization problem is covered off on, right? I've tried the numerous ways that are on SO and still get the same result.

Any help is appreciated!

Dan Hisey
  • 43
  • 1
  • 5
  • Did you check for any typo? Because I don't see anything wrong with your code but you have `model.js` but you're referencing `models/models`. Might be a typo HERE on SO but that's it. – Chau Tran Dec 10 '17 at 20:59
  • @ChauTran You can omit the `.js` extension because it's implied. If it were a typo there would be an error when OP tried to call `Result.find`. – Andrew Li Dec 10 '17 at 21:14
  • Could you try to push to Mongo a new docdument via Node (`new Result({ Owner: 'Test' }).save()`)? Would the shell return it on `db.results.findOne({ Owner: 'Test'})`? would the Node return it on `Result.find()`? – dhilt Dec 10 '17 at 21:26
  • @dhilt When I save an entry, it is not retrievable through the command line, but Node does return it on restart using `Result.find()`. – Dan Hisey Dec 10 '17 at 22:59
  • @DanHisey It means that Node and Shell use different collections or even different databases. As a next step, you may try to list your collections via `db.listCollections()` (shell) and `connection.db.listCollections()` (Node). – dhilt Dec 10 '17 at 23:04
  • @MikaS I thought that was maybe a possibility too. Using `Result.db.host`, `Result.db.name`, and `Result.db.port` it shows `kaplanffl-shard-00-00-rmbku.mongodb.net`, `kaplanFfl`, and `27017`, respectively – Dan Hisey Dec 10 '17 at 23:05
  • @dhilt I had to use`db.getCollectionNames()` in the console, and I got `[ "results" ]` as the response. When I run it in Node, I get the following: `[ { name: 'results', type: 'collection', options: {}, info: { readOnly: false }, idIndex: { v: 2, key: [Object], name: '_id_', ns: 'kaplanFfl.results' } } ]` – Dan Hisey Dec 10 '17 at 23:36
  • @DanHisey And what does say the Mongo Shell about the [DB list](https://stackoverflow.com/questions/25947929/how-to-list-all-databases-in-the-mongo-shell)? – dhilt Dec 10 '17 at 23:38
  • @DanHisey Try to make separate connections: first to `kaplanffl-shard-00-00-rmbku`, second to `...00-01-rmbku` and third to `...02-rmbku`. then try to setup yor model on each of them and make a research... Use [this link](https://stackoverflow.com/a/32909008/3211932) for `createConnection` approach. – dhilt Dec 10 '17 at 23:47
  • @dhilt I connected to localhost and I got the data I was looking for. It has to be something with the separate connections, so I'm going to give your createConnection approach a go. Are the `kaplanffl-shard...` instances pointing to replica sets? I don't believe I ever set up replica sets in mongo – Dan Hisey Dec 11 '17 at 00:09

0 Answers0