An extension of Mongoose's models
$ npm install mongoose-models
var models = ;var Person = models;
var models = ;var Person = models;Person;
Circular references are rather messy in Mongoose. To make this much easier there is built-in support for circular references in mongoose-models. For example, say you have two models:
var models = ;var Bar = models;models;
var models = ;var Foo = models;models;
This doesn't work because the models are trying to reference each other before they have been created. To make this work, we change the
ref value like so in both files:
bar: type: modelstypesObjectId ref: $circular: 'Bar'
foo: type: modelstypesObjectId ref: $circular: 'Foo'
Now everything works as expected. There is also a shorter version of this if a model needs to reference itself recursively.
var models = ;models;
models.require method that loads models does not return the model directly, but instead returns a function that can be used to fetch the model. This is so that when two models make use of each other, the models are allowed time to set themselves up. That is why models are loaded as
models.require(...)(). This returned function has a number of properties on it that can be used as well.
The model function itself (once defined). This is the same as what is returned from the getter function.
The mongoose schema object. This can be accessed immediately without waiting for the model to be created if you need access sooner. This could be used as an alternative to the
$circular syntax described above.
Defines a callback to be run once the model has been created.
var Foo = models;Foo;
$ cp ./node_modules/mongoose-models/bin/repl.js ./repl.js
Now, open up
repl.js and change the values in
conf to match your configuration settings. You can start the REPL by running:
$ node repl.js
The REPL comes with some helpful features on top of the standard node REPL. First, mongoose-models is already loaded for you and is available as
models.require has been patched to automatically store loaded models in
global. There are also some useful functions defined.
Loading REPL...> models;undefined> Foo;...>Stored 2 arguments in "foos"> ;'1': ...'2': ......