I have a collection of warehouse upgrades. It is predefined "template" collection containing for example max_capacity, level and price. Then I have warehouse_levels collection, this contains different indexes to warehouse_upgrades for different stored resources. But I can't create warehouse_level model, because I need to load _ids of warehouse_upgrades
WarehouseUpgrade = mongoose.model("warehouse_upgrade");
// find wheat upgrade containing level 0
WarehouseUpgrade.find({ type: "wheat", level: 0 }).exec(function (err, wheat) {
var warehouseLevelSchema = Schema({
wheat: {
type: Schema.Types.ObjectId,
ref: "warehouse_upgrade",
default: wheat._id
},
... more resources
};
var WarehouseLevel = mongoose.model("warehouse_level", warehouseLevelSchema);
}
When I want to call var WarehouseLevel = mongoose.model("warehouse_level"); interpreting this code throws error:
MissingSchemaError: Schema hasn't been registered for model "warehouse_level"
If I extract out schema definition from WarehouseUpgrade.find, then code works, but I can't set up default values for resource warehouses.
How can I set default value for ObjectId from different collection when I don't want to hardcode this values?
EDIT: I load all schema definitions in file named mongoose.js:
var mongoose = require("mongoose"),
Animal = require("../models/Animal");
Warehouse_upgrade = require("../models/Warehouse_upgrade"),
Warehouse_level = require("../models/Warehouse_level"),
User = require("../models/User"),
...
module.exports = function(config) {
mongoose.connect(config.db);
var db = mongoose.connection;
// And now I call methods for creating my "templates"
Warehouse_upgrade.createUpgrades();
Animal.createAnimals();
User.createDefaultUser();
}
MissingSchemaError occurs in model/User(username, hashed_password, email, warehouse_level,...) - every user has reference to his own document in warehouse_level.
// User
var mongoose = require("mongoose"),
Schema = mongoose.Schema,
Warehouse_level = mongoose.model("warehouse_level");
// There are no users in DB, we need create default ones
// But first, we need to create collection document for warehouse_level
// and warehouse (not shown in this code snippet)
Warehouse_level.create({}, function (err, warehouseLevel) {
if (err) { console.error(err); return; }
// warehouse_level document is created, let's create user
User.create({ username: ..., warehouse_level: warehouseLevel._id });
});