I have these schemas
var DriverSchema = Schema({
name: String,
groups: {
type: String,
ref: 'DriverGroup'
}
});
var DriverGroupSchema = Schema({
name: String
});
module.exports = mongoose.model('DriverGroup', DriverGroupSchema);
module.exports = mongoose.model('Driver', DriverSchema);
I have these driver groups:
[{
id: '12345',
name: 'Group1'
}, {
id: '6789',
name: 'Group2'
}]
and this driver:
{
name: 'Driver1',
groups: '12345,6789'
}
How I can get the groups by population? I am using this:
Driver.find().sort('name').populate('groups')
But does not works properly.
You're storing groups
incorrectly, if you want to populate them in this way.
populate
cannot parse a string in order to determine the separate entities.
It should be an array
groups: '12345,6789'
should be
groups: ['12345,6789']
Also, populate works by looking up the _ids (not name field)
So, will need to change your schema:
var DriverSchema = Schema({
name: String,
groups: [{ type: string, ref: 'DriverGroup' }]
});
You'll need to set the _id
too (set _id
to same as name
in your case)
var DriverGroupSchema = Schema({
_id: String,
name: String
});