John John - 2 months ago 17
Node.js Question

Mongoose populate undefined fields

I see lot of questions about this but I can't find what is wrong. When I'm using populate to get the "Foreign Key" my field is undefined.

User Model :

var userSchema = new Schema({
email : { type: String, required: true, unique: true },
password : { type: String, required: true },
firstname : { type: String, required: true },
lastname : { type: String, required: true },
created_at : Date,
updated_at : Date,
office : [ { type: Schema.Types.ObjectId, ref: 'Office' } ]
});

var User = mongoose.model('User', userSchema, 'User');

module.exports = User;


Office Model :

var officeSchema = new Schema({
name : { type: String, required: true },
address : String,
city : String,
geolocation : [ { type: Schema.Types.ObjectId, ref: 'Geolocation' } ],
company : [ { type: Schema.Types.ObjectId, ref: 'Company' } ]
});

var Office = mongoose.model('Office', officeSchema, 'Office');

module.exports = Office;


Populate code :

User.find({})
.populate('office')
//.populate('office', 'name') I tried this too
.exec(function (err, users) {
if (err) return handleError(err);

users.forEach(function(user){
console.log('Office name: ', user.office.name);
});
});


I want to get the user office name. But this
user.office.name
returns me undefined and when I do this
user.office
I can see the object with the name field. But I don't have the access to the name field.

Answer

The office field in the userSchema is defined as array. So, in order to access its elements, use user.office[0].name, user.office[1].name, etc.

Otherwise, use a loop:

user.office
    .forEach(function(each) {
        console.log('Office name: ', each.name);
    });
Comments