Search code examples
javascriptnode.jsmongodbmean-stackmongoose-populate

Mongoose populate not populating


I am trying to populate my users car inventory. All the cars have a userId attached to them when they are created but when I go to populate the inventory it doesn't work and I get no errors.

Here are my models:

User.js

let UserSchema = mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  inventory: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Car' }]
});

let User = mongoose.model('User', UserSchema);
models.User = User;

Cars.js

let CarSchema = mongoose.Schema({
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  make: {
    type: String,
    required: true
  },
  model: {
    type: String,
    required: true
  },
  year: {
    type: String
  }
});

let Car = mongoose.model('Car', CarSchema);
models.Car = Car;

Here is the populate code:

router.route('/users/:user/inventory').get((req, res) => {
    User.findById(userId)
      .populate('inventory') 
      .exec((err, user) => {
        if (err) {
          console.log("ERRROORRR " + err)
          return res.send(err);
        }

        console.log('Populate ' + user)
        res.status(200).json({message: 'Returned User', data: user});
      });
    });
  };

This is what a car object looks like in the database:

{
  "_id": ObjectId("5759c00d9928cb581b5424d0"),
  "make": "dasda",
  "model": "dafsd",
  "year": "asdfa",
  "userId": ObjectId("575848d8d11e03f611b812cf"),
  "__v": 0
}

Any advice would be great! Thanks!


Solution

  • Populate in Mongoose currently only works with _id's, though there's a long-standing issue to change this. You'll need to make sure your Car model has an _id field and that the inventory field in User is an array of these _id's.

    let CarSchema = new mongoose.Schema(); //implicit _id field - created by mongo
    // Car { _id: 'somerandomstring' }
    
    let UserSchema = new mongoose.Schema({
      inventory: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Car'
      }]
    });
    // User { inventory: ['somerandomstring'] }
    
    User.populate('inventory')