尝试使用对象进行看似相当简单的创建:
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 ofDocumentArray
. This is a special subclassedArray
that can deal withcasting
, 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/