0

I have written the following code, it's for a discord bot. When I call the command I get matchID in console for the first time. But when I call the command again I dont get any output. It gets stuck near the point where I have console.log("Stuck Here"). I new to mongoose so I don't know what to do.

if (mongoose.connection.readyState === 0) {
                mongoose.connect(`mongodb://localhost/${server}`, {
                    useNewUrlParser: true
                });
                console.log('mongoose readyState is ' + mongoose.connection.readyState);
            }

            console.log("Stuck here!");

            mongoose.connection.on("error", function (err) {
                console.log("Could not connect to mongo server!");
                return console.log(err);
            });

            mongoose.connection.on('connected', function (ref) {
                console.log('Connected to mongo server.');

                mongoose.connection.db.listCollections({
                    name: "matches"
                }).next(function (err, collinfo) {
                    if (err) console.log(err);

                    if (collinfo) {
                        Matches.findOne({}, {}, {
                            sort: {
                                'created_at': -1
                            }
                        }, function (err, match) {
                            if (err) console.log(err);

                            console.log(`${match.matchID}`);
                        })
                    } else {
                    }    
                });
            })
ZeuS
  • 13
  • 1
  • 5
  • Your code seems overly complicated. I've never had the need to check the ready state of a connection, for instance: just call `mongoose.connect()` at the top of your code. Also, don't rely on certain events, like `connected`, before performing your queries (one reason for that, and the one you're probably running in to, is that those events only trigger _once_). – robertklep Nov 16 '18 at 19:35
  • If I remove the event `connected` and just connect to database, the `mongoose.connection.db.listCollections` returns as `TypeError: Cannot read property 'listCollections' of undefined` – ZeuS Nov 16 '18 at 19:59
  • Why do you need `listCollections` at all? – robertklep Nov 16 '18 at 20:03
  • On it's inital run there is no database, and bot will establish connection to a pseudo url. And it'll try to look for a collection name `matches` in it. If it doesnt find any, it'll insert a record, making the pseudo db an actual db. And if it already exists I'll get the latest entry from collection `matches` and fetch the last match number and increment it and insert a new record. I'm pretty new to this and this was the only way that came to my mind to execute it, – ZeuS Nov 16 '18 at 20:09
  • So you can have multiple database connections active at once? In that case, you have to be aware that even though Mongoose _can_ work with multiple databases, it isn't trivial to get working. See [this answer](https://stackoverflow.com/a/19475270), for instance: for each connection, you need to recreate all your models. – robertklep Nov 16 '18 at 20:16
  • Yeah that was the plan but seeing the complexity and my skills I'll stick to single server. – ZeuS Nov 16 '18 at 20:18
  • A relatively simple solution would be to use a single database, and add a `server` field to all your models that you can include in each query. So to check if there's a `Matches` document for server "X", you'd run `Matches.findOne({ server : 'X' })`. – robertklep Nov 16 '18 at 20:21
  • Ah like foreign keys, thanks for the idea and helping out! much appreciated. How do I mark the question answered? – ZeuS Nov 16 '18 at 20:30
  • I'll write up a proper answer :D – robertklep Nov 16 '18 at 20:31

1 Answers1

0

Mongoose is really meant to be used with a single database. It isn't impossible to create create multiple connections, or use multiple database, but it's not trivial either. For instance, you have to declare each of your models for each connection/database (see this answer, for instance).

It's probably much easier to use a single database, and adjust your models so they contain a property server that you can use as a key in all your queries.

So to check if there's a Matches document for server "X", you'd run Matches.findOne({ server : 'X' }).

You could also consider creating a separate model Servers that would store metadata for servers, and use references between the Matches and Servers models. More info on that here.

robertklep
  • 198,204
  • 35
  • 394
  • 381