【问题标题】:Saving nested schema in moongose在猫鼬中保存嵌套模式
【发布时间】:2017-06-12 02:06:46
【问题描述】:

我有两个模型

第一个模型

// grab the things we need
var mongoose       = require('mongoose');
// create a schema
var categorySchema = new mongoose.Schema({
  name       : String,
  description: String,
  active     : Boolean,
  createdDate: {type: Date, default: Date.now},
  updatedDate: {type: Date, default: ''}
});
var category       = mongoose.model('Category', categorySchema);
module.exports     = category;

第二个模型

var mongoose      = require('mongoose');
// create a schema
var productSchema = new mongoose.Schema({
  product_name: String,
  manufacturer: String,
  category    : {type: mongoose.Schema.ObjectId, ref: 'Category'}
});
var user          = mongoose.model('Product', productSchema);
module.exports    = user;

这是我使用的模型:

module.exports.CreateProdct = function(Channel_Object, callback) {
  product = new Product({
    product_name: Channel_Object.product_name,
    manufacturer: Channel_Object.manufacturer,
    category    : Channel_Object.category,
  });

  product.save(function(err, customer) {

    if (err)
      console.log(err)
    else
      callback(customer);

  });
}

保存产品架构时出现错误:

{ category:
  { [CastError: Cast to ObjectID failed for value "{ name: 'bus', descriptio
   n: 'dskflsdflsdkf', active: true }" at path "category"]

这是项目的 json

{
  "product_name": "ppsi",
  "manufacturer": "fanta",
  "category"    : {
    "name"       : "bus",
    "description": "dskflsdflsdkf",
    "active"     : true
  }
}

这是产品模型的 JSON。我在产品模型中嵌入了类别,它显示“Cast to ObjectID failed for value”。

【问题讨论】:

    标签: node.js mongoose mean-stack


    【解决方案1】:

    在您的 product schema 中,您已将 category 定义为引用字段 (ref : 'Category') 。它需要一个ObjectId,但在您的CreateProdct 函数中,您将整个对象传递给它。

    这就是它显示此错误的原因:

    [CastError: Cast to ObjectID failed for value "{ name: 'bus', 描述:'dskflsdflsdkf',活动:true }" 在路径 "category"]。

    尝试先保存category,然后在categorysuccessful creation 上将其_id 传递给product 文档,然后将save 传递给它。

    试试这个:

    module.exports.CreateProdct = function(Channel_Object, callback) {
    
      var category = new Category(Channel_Object.category);
      category.save(function(err,category)
      {
        if(!err)
        {
          product = new Product({
            product_name: Channel_Object.product_name,
            manufacturer: Channel_Object.manufacturer,
            category: category._id
          });
    
          product.save(function(err2,customer){
    
            if(err)
              console.log(err2)
            else  
              callback(customer);
    
         });
        }
        else{
          console.log(err);
          //handle the case where it throws error too.
        }
      })
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-22
      • 2014-02-10
      • 2019-07-20
      • 1970-01-01
      • 2015-09-21
      • 2014-06-22
      • 2014-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多