2017-04-24 84 views
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上发射插入(保存)查询。

有与这些几个问题:

  1. 如何确保,同时加入了产品,我也添加它挂类别?
  2. 对于这种情况(添加子文档或引用模式),最佳做法是什么?

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"] 
    } 
    .... 
} 

回答

0

更改type键来mongoose.Schema.Types.ObjectId值就会使链接到要引用,并填入的帮助,您可以通过.populate('parent')拨打电话到整个父模式这是perticular的ObjectId。

对于我的详细信息reffer这样: - populate

感谢。

+0

但是当我添加mongoose.Schema.Types.ObjectId,我尝试以下列方式插入数据: { \t “名”: “LG G4”, \t “照片”:“HTTP://谷歌”, \t “价格”:{ \t \t “量”:300, \t \t “货币”: “USD” \t}, \t “类别”: “笔记本电脑” }我得到铸造错误到的ObjectId 。我将在此阅读关于填充的内容。 – Hardik

+0

这样做: - category:'{type:mongoose.Schema.Types.ObjectId,ref:'category'}'不要输入_id mannualy,因为mongodb会自动提供_id给数据库,数据库(随机ObjectId) – hardy

+0

,但我仍然收到消息:'铸造ObjectID失败的价值'错误。 – Hardik