gpt4 book ai didi

node.js - Mongoose Schema 的 ObjectId 默认值

转载 作者:太空宇宙 更新时间:2023-11-04 02:22:41 27 4
gpt4 key购买 nike

我有一系列仓库升级。它是预定义的"template"集合,包含例如 max_capacity、级别和价格。然后我有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 发生在模型/用户(用户名、散列密码、电子邮件、仓库级别...)中 - 每个用户都在仓库级别中引用了自己的文档。

// 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 });
});

最佳答案

实现此目的的一种可能方法是创建一个类似“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();
});

关于node.js - Mongoose Schema 的 ObjectId 默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32320342/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com