我有一系列仓库升级。它是预定义的“模板”集合,包含例如max_capacity,level和price。然后我有了warehouse_levels集合,它包含针对不同存储资源的warehouse_upgrades的不同索引。但我无法创建warehouse_level模型,因为我需要加载warehouse_upgrades的_id
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);
}
当我想调用var WarehouseLevel = mongoose.model(“warehouse_level”);解释此代码会引发错误:
MissingSchemaError: Schema hasn't been registered for model "warehouse_level"
如果我从WarehouseUpgrade.find中提取出架构定义,那么代码可以工作,但是我无法为资源仓库设置默认值。
如果我不想对这些值进行硬编码,如何从不同的集合中设置ObjectId的默认值?
编辑: 我在名为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出现在model / User(用户名,hashed_password,email,warehouse_level,...)中 - 每个用户都在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 });
});
答案 0 :(得分:0)
实现这一目标的一种可能方法是创建类似" setDefaultIndexes"
的方法var warehouseLevelSchema = mongoose.Schema({..});
warehouseLevelSchema.methods = {
setDefaultUpgrades: function() {
var self = this;
WarehouseUpgrade.find({ level: 0 }).exec(function (err, collection) {
for (var i = 0; i < collection.length; i++) {
var upgrade = collection[i];
self[upgrade.type] = upgrade._id;
}
self.save();
});
}
};
var Warehouse_level = mongoose.model("warehouse_level", warehouseLevelSchema);
在创建新的warehouse_level之后调用它:
WarehouseLevel.create({}, function (err, warehouseLevel) {
if (err) { console.error(err); return; }
warehouseLevel.setDefaultUpgrades();
});