Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose connection/models: Need to always run on open?

I am using Mongoose 3 and the most obvious way to connect to database is

conn = mongoose.createConnection(...)
conn.on("open", ...)

Question is, do I need to define all my models in the open callback? If that is so, I will have to create a initMongoose.coffee that looks like

# initMongoose.coffee

mongoose = require "mongoose"
module.exports = mongoose.createConnection ...

# modelExample.coffee

conn = require "./initDatabase"
conn.on "open", -> 
    ... define model?
    modeule.exports = model # I think this does not work?

I think I read somewhere in Node docs that modules cannot be defined in a callback like that?


Since I am only using 1 connection, I think I can use

mongoose.connect ...

Which doesnt accepts any callbacks so I suppose is synchronous? Can I define all my models and thus queries right after connect()? It works at the moment, but it might be because its fast enough.

like image 748
Jiew Meng Avatar asked Aug 11 '12 00:08

Jiew Meng


1 Answers

Mongoose buffers up commands until it is finished connecting, so you can treat it like it's synchronous and define your models and start using the library whenever you want; only once you want to start actually inserting or retrieving data do you need to make the connection.

like image 129
Michelle Tilley Avatar answered Sep 28 '22 18:09

Michelle Tilley