Reputation: 2769
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 protected]', _id: 532e570864803bf505e51c81 } ]
I would expect this:
[ { _department: { _id: 532c77c3485925d806436981, name: 'bar' },
email: '[email protected]',
_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 protected]',
_id: 532e570864803bf505e51c81,
__v: 0 } ]
What makes me wonder that the select is breaking the populate. My mongoose version is 3.8.8
Upvotes: 1
Views: 10384
Reputation: 2999
Try my code:
const Employee= require('../models/employee');
Employee.find({}, 'email _department')
.populate('_department', ['name'])
.exec(function(err, list_employee) {
if (err) { return next(err); }
//Successful
console.log(list_employee);
});
Will work for you!
Upvotes: 1
Reputation: 1
Work for me this in mongoose and here company_name field is getting populate via reference ModelName.find().populate('parent_id', 'company_name') .select('username mobile firstname lastname company_name');
Upvotes: 0
Reputation: 151170
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);
});
Upvotes: 7