Randy Hall
Randy Hall

Reputation: 8167

Mongoose create record containing an array of objects (Cast to Array failed)

Attempting what seems like a fairly straightforward create using object:

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

into schema:

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

via:

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

And I'm getting:

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

Am I missing something blatantly obvious here?

EDIT Added "car_id" field to my example. My actual schema/document is large and somewhat dynamically created. I'm trying to be as precise as possible without being too accurate for disclosure purposes. I can't post actual data here.

Upvotes: 2

Views: 770

Answers (1)

Abdullah Rasheed
Abdullah Rasheed

Reputation: 3752

According the docs, you should handle your embedded documents like so:

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.

You could then add a cars document like so:

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

Upvotes: 2

Related Questions