I have a Person model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PersonSchema = new Schema({
name: String,
cars: [{
type: Schema.types.ObjectId,
ref: 'Cars'
}]
});
const Person = module.exports = mongoose.model('Person', PersonSchema);
and I have a Cars model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CarsSchema = new Schema({
color: String,
owner: {
type: Schema.Types.ObjectId,
ref: 'Person'
},
});
const Cars = module.exports = mongoose.model('Cars', CarsSchema);
How do I make sure that every time a car is added, it get listed in a particular person's car array?
Right now, I've done something like this:
const newPerson = new Person({
name: 'jared'
});
newPerson.save()
.then(person => {
console.log(person);
});
const newCar = new Car({
color: 'red'
});
newCar.save(function(err, car) {
if (err) {
console.log(err)
} else {
car.populate(
car, {
path: "owner"
},
function(err, car) {
if (err) {
console.log(err);
} else {
console.log(car);
}
});
}
});
the code works without errors, and the car gets properly printed to the terminal with the "jared" person document seen occupying the owner field, but the result isn't saved to MongoDB. Instead, when I check MongoDB, I just see the car with only the "jared" document _id occupying the owner field. Can anyone please tell me why that is?