在moongose中保存嵌套模式

时间:2017-01-26 14:54:25

标签: node.js mongoose mean-stack

我有两个模特

第一个模型

// 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因值而失败"。

1 个答案:

答案 0 :(得分:1)

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

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

  

[CastError:对于值“{name:'bus',施放到ObjectID失败,   描述:'dskflsdflsdkf',活跃:true}“在路径”类别“]。

首先尝试保存category,然后successful creation category将其_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.
    }
  })

}