How do I successfully populate a mongoose schema?

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?

Start a personal dev blog on your domain for free and grow your readership.

3.4K+ developers have started their personal blogs on Hashnode in the last one month.

Write in Markdown 路 Publish articles on custom domain 路 Gain readership on day zero 路 Automatic GitHub backup and more

Comments (4)

Sai Kishore Komanduri's photo

The reason that you only see the ID is because that's how you have defined your CarsSchema.

const CarsSchema = new Schema({
    color: String,
    owner: {
        type: Schema.Types.ObjectId,
        ref: 'Person'
    },
});

The owner field in a document from the Cars collection just stores the ObjectId of the corresponding document from Persons collection.

...and whenever you need access to the details of the corresponding Person document, you would use mongoose's populate, which just queries the corresponding document, and fills in the required details for you.

Citing from Mongoose docs:

There are no joins in MongoDB but sometimes we still want references to documents in other collections. This is where population comes in.

Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). We may populate a single document, multiple documents, plain object, multiple plain objects, or all objects returned from a query.

Please do ask, if you have any more questions! :)