【问题标题】:Nesting MongoDB Schema嵌套 MongoDB 模式
【发布时间】: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

还有几个与这些相关的问题:

  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);

产品的示例输出结构:

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

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    type 键的值更改为mongoose.Schema.Types.ObjectId,它将链接到您要引用的特定ObjectId,并且在填充的帮助下,您可以通过.populate('parent') 调用整个父架构。

    有关我的更多信息,请参阅:- populate

    谢谢。

    【讨论】:

    • 但是当我添加 mongoose.Schema.Types.ObjectId 时,我尝试按以下方式插入数据:{ "name":"LG G4", "pictures":"google" , "price":{ "amount":300, "currency":"USD" }, "category":"Laptops" } 我收到转换错误到 ObjectId。同时我将阅读有关填充的内容。
    • 这样做:- category:` { type: mongoose.Schema.Types.ObjectId, ref: 'category' } ` 不要手动输入_id,因为mongodb会自动提供_id在整个数据库中唯一的数据库(随机 ObjectId)
    • 但我仍然收到消息:'Cast to ObjectID failed for value' 错误。
    猜你喜欢
    • 2021-06-29
    • 1970-01-01
    • 2021-06-21
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 2018-08-03
    • 1970-01-01
    相关资源
    最近更新 更多