在猫鼬中保存嵌套模式

Saving nested schema in moongose

我有两个模型

第一个模型

// 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"。

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

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

[CastError: Cast to ObjectID failed for value "{ name: 'bus', description: 'dskflsdflsdkf', active: true }" at path "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.
    }
  })

}