arrays - Mongoose 创建包含对象数组的记录(转换为数组失败)

标签 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”字段。我的实际架构/文档很大并且有点动态创建。我试图尽可能准确,但又不会为了披露目的而过于准确。我无法在这里发布实际数据。

最佳答案

根据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);

This way your The cars key of your People documents will then be an instance of DocumentArray. This is a special subclassed Array that can deal with casting, and has special methods to work with embedded documents.

然后您可以添加一个汽车文档,如下所示:

// 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!');
});

关于arrays - Mongoose 创建包含对象数组的记录(转换为数组失败),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33701702/

相关文章:

javascript - 如何避免 undefined 不是一个函数

mongodb - Spring-Data:指定 MongoRepository 应该使用哪个 MongoTemplate

mongodb - Meteor:如何在启动时删除所有 Mongo 集合并清除所有数据?

java - 如何将对象列表转换为多维数组

javascript - 在多个数组中查找唯一值

javascript - nodejs中REPL的使用

node.js - 我应该如何加载我自己的模块内的文件?

javascript - 如何将字符串循环为键值对

arrays - 当我对数组 B 进行排序时,数组 A 的内容发生了变化,数组 B 应该是 A 的重复项

mongodb - 即使在 MongoDB 集合上完成创建索引后,内存使用率仍保持 99%