2

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.

1
  • @inspired good thought. I tried it, and confirmed that the date objects are being passed correctly. Unfortunately, I'm still getting the same error. Commented Nov 13, 2015 at 21:32

1 Answer 1

2

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!');
});
Sign up to request clarification or add additional context in comments.

1 Comment

Had to modify a ton of stuff (my semi-dynamic schema reader was relying on schema.tree for some things) but this worked beautifully! Thanks, I've been at this one for hours.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.