我一直在他们网站上托管的Webinar网上学习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"]
}
....
}
答案 0 :(得分:0)
将type
键的值更改为mongoose.Schema.Types.ObjectId
它将链接到您想要引用的特定ObjectId,并且在填充的帮助下,您可以通过{{调用整个父模式1}}。
有关我的更多信息: - populate
感谢。