0
我一直在從他們的網站上託管的在線Webinar學習MongoDB,並且我試圖將產品鏈接到一個類別(例如,iPhone屬於具有諸如電子的祖先的類別移動設備),但是在嵌套我收到以下錯誤:嵌套MongoDB架構
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);
示例P輸出結構RODUCT:
{
"_id": "**autogeneratedByMongo",
"name":"iPhone",
"category":{
"_id":"Mobiles",
"ancestors":["Electronics","Mobiles"]
}
....
}
但是當我添加mongoose.Schema.Types.ObjectId,我嘗試以下列方式插入數據: { \t 「名」: 「LG G4」, \t 「照片」:「HTTP://谷歌」, \t 「價格」:{ \t \t 「量」:300, \t \t 「貨幣」: 「USD」 \t}, \t 「類別」: 「筆記本電腦」 }我得到鑄造錯誤到的ObjectId 。我將在此閱讀關於填充的內容。 – Hardik
這樣做: - category:'{type:mongoose.Schema.Types.ObjectId,ref:'category'}'不要輸入_id mannualy,因爲mongodb會自動提供_id給數據庫,數據庫(隨機ObjectId) – hardy
,但我仍然收到消息:'鑄造ObjectID失敗的價值'錯誤。 – Hardik