我一直在他们的网站上托管的在线网络研讨会中学习MongoDB,我正在尝试将产品链接到类别(例如,iPhone属于具有电子产品祖先的类别手机(,但是,在嵌套时,我会收到以下错误:
MongooseError: Schema hasn't been registered for model "Category".
Use mongoose.model(name, schema)
我通过编写schema.ObjectID和schema.types.objectid看到了几个问题,但是我在启动插入(保存(查询时得到了Cast Error to ObjectId
。
与这些问题有关的其他问题:
- 如何确保在添加产品时,我还添加了它链接到的类别?
- 对于这种情况(添加子图案或参考模式(的最佳实践是什么?
pfb模型文件,我在其中的书面控制器文件以执行CRUD操作:
category.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var categorySchema = new Schema({
_id: { type: String },
parent: {
type: String,
ref: 'Category'
},
ancestors: [{
type: String,
ref: 'Category'
}]
});
module.exports.categorySchema = categorySchema;
products.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Category = require('./category');
var fx = require('./fx');
var productSchema = new mongoose.Schema({
name: { type: String, required: true },
// Pictures must start with "http://"
pictures: [{ type: String, match: /^http:///i }],
price: {
amount: {
type: Number,
required: true,
set: function(v) {
this.internal.approximatePriceUSD =
v / (fx()[this.price.currency] || 1);
return v;
}
},
// Only 3 supported currencies for now
currency: {
type: String,
enum: ['USD', 'EUR', 'GBP'],
required: true,
set: function(v) {
this.internal.approximatePriceUSD =
this.price.amount / (fx()[v] || 1);
return v;
}
}
},
category: { type: Schema.ObjectId,ref: 'Category'},
internal: {
approximatePriceUSD: Number
}
});
//var schema = new mongoose.Schema(productSchema);
var currencySymbols = {
'USD': '$',
'EUR': '€',
'GBP': '£'
};
/*
* Human-readable string form of price - "$25" rather
* than "25 USD"
*/
productSchema.virtual('displayPrice').get(function() {
return currencySymbols[this.price.currency] +
'' + this.price.amount;
});
productSchema.set('toObject', { virtuals: true });
productSchema.set('toJSON', { virtuals: true });
module.exports = mongoose.model("Product", productSchema);
产品的输出结构:
{
"_id": "**autogeneratedByMongo",
"name":"iPhone",
"category":{
"_id":"Mobiles",
"ancestors":["Electronics","Mobiles"]
}
....
}
将 type
键的值更改为 mongoose.Schema.Types.ObjectId
,它将链接到您要引用的perticular objectid,并在填充的帮助下,可以通过 .populate('parent')
呼叫整个父架。
有关此信息的更多信息: - 填充
谢谢。