【发布时间】:2015-11-26 00:35:52
【问题描述】:
我有一系列仓库升级。它是预定义的“模板”集合,包含例如 max_capacity、level 和 price。然后我有warehouse_levels 集合,它包含针对不同存储资源的warehouse_upgrades 的不同索引。但是我不能创建warehouse_level模型,因为我需要加载warehouse_upgrades的_ids
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(username, 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 });
});
【问题讨论】:
-
您可能必须在默认键中使用一个对象,例如 default: {
-
Hi 是 Schema 定义为:var Schema = DB.mongoose.Schema;
-
var Schema = DB.mongoose.Schema;抛出错误 - 引用错误 - 未定义数据库
-
那么您是如何定义数据库的,您将数据库附加到何处? Schema 没有直接定义,只有 mongoose.Schema 存在。
标签: node.js mongodb mongoose schema odm