Mongoose创建包含对象数组的记录(Cast to Array失败)

时间:2015-11-13 21:01:56

标签: arrays node.js mongodb mongoose

尝试使用对象创建一个相当简单的东西:

var toSave = {
  person_number: "rjq8900",
  person_name: "john smith",
  cars: [{
    car_id: "fordTaurus1994",
    make: "ford",
    model: "taurus",
    purchased: "31-Aug-15",
    price: "1650"
  }]
}

进入架构:

var People = new Schema({
  person_number: String,
  person_name: String,
  cars:[{
    car_id: String,
    make: String,
    model: String,
    purchased: Date,
    price: Number
  }]
})

通过:

People.create(toSave, function(e, doc){
  console.log(e);
});

我得到了:

errors:{
  cars:{
    [CastError: Cast to Array failed for value "[object Object]" at path "cars"]
  }
}

我错过了一些明显明显的东西吗?

修改 添加" car_id"我的例子。我的实际架构/文档很大,有些动态创建。我试图尽可能精确,而不是为了披露目的太准确。我无法在此处发布实际数据。

1 个答案:

答案 0 :(得分:1)

根据docs,您应该像这样处理嵌入式文档:

var Cars = new Schema({
  car_id: String,
  make: String,
  model: String,
  purchased: Date,
  price: Number
});

var People = new Schema({
  person_number: String,
  person_name: String,
  cars:[Cars]
});

mongoose.model('People',People);
  

这样,您的人员文档的cars密钥就会成为   DocumentArray的实例。这是一个特殊的子类Array可以   处理casting,并有特殊的方法来使用嵌入式   文档。

然后您可以像这样添加汽车文档:

// retrieve my model
var Car= mongoose.model('Car');

// create a person
var person = new Person();

// push car
person.cars.push(
{
    car_id: "fordTaurus1994",
    make: "ford",
    model: "taurus",
    purchased: "31-Aug-15",
    price: "1650"
  }
);

person.save(function (err) {
  if (!err) console.log('Success!');
});