简体   繁体   English

嵌套MongoDB模式

[英]Nesting MongoDB Schema

I've been learning MongoDB from their online Webinar hosted on their website and I'm trying to link Products to a Category (eg. iPhone belongs to Category Mobiles which has ancestors such as Electronics ), however while nesting I'm getting the following error: 我一直在从其网站上托管的在线网络研讨会上学习MongoDB,并尝试将产品链接到某个类别(例如,iPhone属于拥有诸如电子之类的祖先的Category Mobiles),但是在嵌套时,我得到了以下内容错误:

MongooseError: Schema hasn't been registered for model "Category".
Use mongoose.model(name, schema)

I saw several questions, by writing Schema.ObjectId and Schema.Types.ObjectId, but I get Cast Error to ObjectId on firing an insert(save) query. 我通过编写Schema.ObjectId和Schema.Types.ObjectId看到了几个问题,但是在触发insert(save)查询时,我将Cast Error to ObjectId

There are few more questions related to these: 与这些相关的问题很少:

  1. How do I make sure, while adding a Product, I also add the Category it's linked to? 如何确保在添加产品的同时添加链接到的类别?
  2. What would be a best practice for such kind of scenario (to add subdocuments or reference Schemas)? 对于这种情况(添加子文档或参考架构),最佳做法是什么?

PFB Model files, I have written Controller files on top of that in order to perform CRUD operations: PFB模型文件,为了执行CRUD操作,我在上面写了Controller文件:

category.js 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 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);

Example Output Structure of a Product: 产品的输出结构示例:

{
    "_id": "**autogeneratedByMongo",
    "name":"iPhone",
    "category":{
        "_id":"Mobiles", 
        "ancestors":["Electronics","Mobiles"]
    }
    ....
}

Change the value of the type key to mongoose.Schema.Types.ObjectId it will make link to that perticular ObjectId to which you want to refer and with help of populate you can make call to whole parent schema by .populate('parent') . type键的值更改为mongoose.Schema.Types.ObjectId ,它将链接到您要引用的.populate('parent') ObjectId,并借助填充,您可以通过.populate('parent')调用整个父模式。

For more info of I reffer to this :- populate 有关我的更多信息,请参考:- 填充

Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM