/
Write
Start a team blog
NEW ✨
Start a team blog, invite your team, and start publishing.

How do I successfully populate a mongoose schema?

Emmanuel's photo
Emmanuel
·May 24, 2017

for example, if 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 had 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.

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);   
                     } 
          });
....
//  I also forgot to add that I already included the _id from the person to the car owner

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 persisted 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?