Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 嵌套MongoDB模式_Node.js_Mongodb_Express_Mongoose - Fatal编程技术网

Node.js 嵌套MongoDB模式

Node.js 嵌套MongoDB模式,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我一直在从MongoDB网站上的在线主机学习MongoDB,我试图将产品链接到一个类别(例如,iPhone属于手机类别,它的祖先是电子产品),但是在嵌套时,我遇到了以下错误: MongooseError: Schema hasn't been registered for model "Category". Use mongoose.model(name, schema) 通过编写Schema.ObjectId和Schema.Types.ObjectId,我看到了几个问题,但在触发插入(保存)

我一直在从MongoDB网站上的在线主机学习MongoDB,我试图将产品链接到一个类别(例如,iPhone属于手机类别,它的祖先是电子产品),但是在嵌套时,我遇到了以下错误:

MongooseError: Schema hasn't been registered for model "Category".
Use mongoose.model(name, schema)
通过编写Schema.ObjectId和Schema.Types.ObjectId,我看到了几个问题,但在触发插入(保存)查询时,我将
错误转换为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;
    
    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);
    
    products.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;
    
    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"]
        }
        ....
    }
    

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

    欲了解更多信息,请参阅:


    谢谢。

    但是当我添加mongoose.Schema.Types.ObjectId时,我尝试以以下方式插入数据:{“name”:“LG G4”,“pictures”:“price”:{“amount”:300,“currency”:“USD”},“category”:“Laptops”},我将错误转换为ObjectId。我将同时阅读关于populate的内容。这样做:-category:`{type:mongoose.Schema.Types.ObjectId,ref:'category'}`并且不要手动输入_id,因为mongodb将自动向数据库提供_id,该id在整个数据库中都是唯一的(随机ObjectId),但我仍然会收到消息:“值转换为ObjectId失败”错误。