I have a very simple \"server.js\" setup that I am trying to run:
var express = require(\'express\'),
wines = require(\'./routes/testscripts\');
var app = e
If you connected to the database already, the once
event won't fire again. The database was already connected for the entire NodeJs process when it was globally connected (outside of the function).
The call to mongoose.connect('mongodb://localhost/test');
makes the connection and opens it.
So, instead of opening it on each function call (which would be an inefficient way to interact with MongoDB) connect
right away when the NodeJs app is started, and consider that there will be a period where the connection may not be available (as it's async), or don't start the app (listen
) until the connection is complete (or with a timeout). With Mongoose, until the connection is made, all commands are buffered (but that may not be the behavior you want). You can use the open
event if you want to know when the connection is complete.
The connection is found here: mongoose.connection
if you use the connect
function to create the connection.
Once the connection is opened, you can use it from your popSingleData
function without using the once
event and callback. There's a connection pool automatically maintained.
For more about connections, read here.