Mongoose query doesn't run when readyState is 1












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 {
}
});
})









share|improve this question

























  • 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, for instance: for each connection, you need to recreate all your models.

    – robertklep
    Nov 16 '18 at 20:16


















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 {
}
});
})









share|improve this question

























  • 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, for instance: for each connection, you need to recreate all your models.

    – robertklep
    Nov 16 '18 at 20:16
















0












0








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 {
}
});
})









share|improve this question
















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 {
}
});
})






javascript node.js mongodb mongoose






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 20:02







ZeuS

















asked Nov 16 '18 at 18:55









ZeuSZeuS

33




33













  • 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, for instance: for each connection, you need to recreate all your models.

    – robertklep
    Nov 16 '18 at 20:16





















  • 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, for instance: for each connection, you need to recreate all your models.

    – robertklep
    Nov 16 '18 at 20:16



















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





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





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





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





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, for instance: for each connection, you need to recreate all your models.

– robertklep
Nov 16 '18 at 20:16







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, for instance: for each connection, you need to recreate all your models.

– robertklep
Nov 16 '18 at 20:16














1 Answer
1






active

oldest

votes


















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.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53343829%2fmongoose-query-doesnt-run-when-readystate-is-1%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    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.






    share|improve this answer




























      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.






      share|improve this answer


























        0












        0








        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.






        share|improve this answer













        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.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 16 '18 at 20:42









        robertkleprobertklep

        136k18234243




        136k18234243






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53343829%2fmongoose-query-doesnt-run-when-readystate-is-1%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to pass form data using jquery Ajax to insert data in database?

            National Museum of Racing and Hall of Fame

            Guess what letter conforming each word