Search code examples
mongoose-models

Mongoose models not written to mongoose.models object. Problem?


I am building a Nodejs/Mongoose backend and I have one MongoDB Atlas cluster with two databases: A and B.

I have connected to database A en B with createConnection(). Like so:

const connectDB = (url) => {
  return mongoose
  .createConnection(url, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
    useUnifiedTopology: true
  })
}

const A = connectDB( *theURI* )
const B = connectDB( *theURI* )

The models I have set up for the databases are created as follows (for example for database A):

const fruit = A.model('fruit', fruitSchema)
const animal = A.model('animal', animalSchema)

module.exports = {
  fruit,
  animal
}

Now I try to access the mongoose.models object, to see an overview of my models (because I need it). My models don't show up. When I create the models with mongoose.model instead of A.model, they do show up.

I fail to see the significance of this, however. Did I set up my models wrong (although it does function)? Am I bound to run into trouble with my code if I don't use mongoose.model?

Thank you.


Solution

  • I think I understand now. Instead of deleting the post, I'll explain what helped me understand.

    Apparently, Mongoose distinguishes the 'default' connection and 'non-default' connections. You can make only one default connection (with mongoose.connect), but multiple ones that are not of the default type (with .createConnection).

    Models are assigned to a connection -- whether default or not. My models are assigned to A and B, and can be accessed via A.models or B.models.

    No problem whatsoever, from what I understand, to set up connections and models the way I did. I hope, anyway.