FabioCosta FabioCosta - 4 months ago 87
Node.js Question

Mongoose select with populate not working

I am making a query in mogoose and if i add any parameter on a query select, the populate parameter goes missing for example i have the following schemas:

Department:

var mongoose = require('mongoose');
var schema = mongoose.Schema({
name: {type:String,required: true,index: {unique: true}} ,
text: String
})

module.exports=mongoose.model('Department',schema);


Employee:

var mongoose = require('mongoose');
var ObjectId=mongoose.Schema.ObjectId;

var schema = mongoose.Schema({
name: {type:String,required: true} ,
lastName: {type:String} ,
birthday:Date,
email:{type:String,required: true,index: {unique: true}},
_department:{type:ObjectId,ref:'Department'},
isUser:Boolean
},{ strict:false});
module.exports=mongoose.model('Employee',schema);


if i make:

var query=mongoose.model('Employee').find();
query.select('email').populate('_department','name');
query.exec(function(err,data){
console.log(data);
});


I get the following ouput

[ { email: 'email@email.com.br', _id: 532e570864803bf505e51c81 } ]


I would expect this:

[ { _department: { _id: 532c77c3485925d806436981, name: 'bar' },
email: 'email@email.com.br',
_id: 532e570864803bf505e51c81,
__v: 0 } ]


If i make the following:

var query=mongoose.model('Employee').find();
query.populate('_department','name');
query.exec(function(err,data){
console.log(data);
});


I get this output

[ { _department: { _id: 532c77c3485925d806436981, name: 'bar' },
name: 'mimimi',
email: 'email@email.com.br',
_id: 532e570864803bf505e51c81,
__v: 0 } ]


What makes me wonder that the select is breaking the populate.
My mongoose version is 3.8.8

Answer

Surely you just specify the fields you want. Currently you only have "email" so that is all you get:

var query=mongoose.model('Employee').find();
query.select('email _department').populate('_department','name');
query.exec(function(err,data){
    console.log(data);
});
Comments