3

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!

Sonicd300
  • 1,950
  • 1
  • 16
  • 22
JuniorSauce
  • 227
  • 3
  • 9

1 Answers1

4

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')
Sonicd300
  • 1,950
  • 1
  • 16
  • 22
Jack Guy
  • 8,346
  • 8
  • 55
  • 86
  • So I need to add a _id field to my car model? Mongo automatically creates that for you when you save to the db. Are they not linked up the way that I currently have them? I thought the userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, and inventory: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Car' }] was doing that. – JuniorSauce Jun 09 '16 at 22:03
  • JuniorSauce which field from "Car" are you storing in that array? It should be `_id`. – Jack Guy Jun 09 '16 at 22:05
  • The inventory field in the User model should be doing that. – JuniorSauce Jun 09 '16 at 22:07
  • JuniorSauce, not if you aren't saving the cars in the inventory correctly. Which is what I'd guess the problem is. – Jack Guy Jun 09 '16 at 22:08
  • Oh I thought the populate would do that by picking up the userId. So I need to save the cars to the inventory some how. This is confusing haha. Thank you for your help. – JuniorSauce Jun 09 '16 at 22:19
  • Yeah JuniorSauce just make sure when you look at your User data in Mongo that the "inventories" is a list of `_id`s that correspond to `_id`s of Cars – Jack Guy Jun 09 '16 at 22:27
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/114287/discussion-between-juniorsauce-and-harangue). – JuniorSauce Jun 09 '16 at 22:40