A
A
Alexander Wolf2013-10-05 23:23:53
NoSQL
Alexander Wolf, 2013-10-05 23:23:53

Checking for model existence in mongoose

Hello! I have a function

function getModel (db) {
  return db.model('Test', Test, 'test');
}

And when using it in the code > 1 time, node.js crashes with an error message:
Cannot overwrite `Test` model once compiled.

The only way I found is to check for the existence of the model
function getModel (db) {
  var name = 'Test';
  if (db.model(name)) return db.model(name);
  else return db.model(name, Test, 'test');
}

I wanted to know if this is correct? Or is there a more convenient and logical way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kxyu, 2013-10-06
@mannaro

There are many other options, but this one is good. For readability, you can write it like this:

function getModel (db) {
    var name = 'Test';
    return db.model(name) || db.model(name, Test, 'test');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question