Error que me da la consola al querer hacer la petición Post agregando un auto a la colección de autos que se encuentra dentro del modelo de cliente:
(node:12176) UnhandledPromiseRejectionWarning: ValidationError: Car validation failed: client: Cast to ObjectId failed for value "[ { nombre: 'Ford', apellido: 'Fiat' } ]" at path "client"
Modelo auto
const { Schema, model } = require('mongoose');
let CarSchema = new Schema({
model: { type: String, required: [true, "the model field is required"] },
colour: { type: String, required: [true, "the colour field is required"] },
client: {
type: Schema.Types.ObjectId,
ref: "Client",
required: true
},
});
CarSchema.methods.toJSON = function () {
const { __v, ...data } = this.toObject();
return data;
};
Modelo cliente
module.exports = model( 'Car', CarSchema );
const { Schema, model } = require('mongoose');
let ClientSchema = new Schema({
nombre: {
type: String,
required: [true, 'El nombre es obligatorio']
},
apellido: {
type: String,
required: [true, 'El correo es obligatorio']
},
car: [
{ type: Schema.Types.ObjectId, ref: 'car' ,
required: [true, 'El auto es obligatorio']
}],
});
ClientSchema.methods.toJSON = function() {
const { __v, ...client } = this.toObject();
client.id = _id;
return client;
}
module.exports = model( 'Client', ClientSchema );
ControladorCar
let Car = require('../models/car');
const mongoose = require('mongoose');
exports.car_create_post = async function(req, res) {
const car = new Car(req.body);
delete car._id;
await car.save();
const client = await Client.findById({_id: car.client})
client.car.push(car);
await client.save();
res.status(200).json({success:true, data: car })
};