【发布时间】:2017-09-21 05:16:36
【问题描述】:
我一直在从他们网站上托管的在线Webinar 中学习 MongoDB,我正在尝试将 Products 链接到一个类别(例如,iPhone 属于具有诸如 Electronics 之类的祖先的 Mobiles 类别),但是在嵌套时我'收到以下错误:
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"]
}
....
}
【问题讨论】:
标签: node.js mongodb express mongoose