繁体   English   中英

在Moongose中保存嵌套模式

[英]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。 我将类别嵌入产品模型中,该类别显示“对ObjectID的转换无法获取值”。

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

这就是为什么它显示此错误:

[CastError:在路径“类别”处,对于值“ {{名称:'bus',描述:'dskflsdflsdkf',活动:true}”,转换为ObjectID失败]]。

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM