我在mogoose中进行查询,如果我在查询选择中添加任何参数,则populate参数会丢失,例如我有以下模式:
系:
var mongoose = require('mongoose');
var schema = mongoose.Schema({
name: {type:String,required: true,index: {unique: true}} ,
text: String
})
module.exports=mongoose.model('Department',schema);
员工:
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);
如果我做:
var query=mongoose.model('Employee').find();
query.select('email').populate('_department','name');
query.exec(function(err,data){
console.log(data);
});
我得到以下输出
[ { email: 'email@email.com.br', _id: 532e570864803bf505e51c81 } ]
我希望如此:
[ { _department: { _id: 532c77c3485925d806436981, name: 'bar' },
email: 'email@email.com.br',
_id: 532e570864803bf505e51c81,
__v: 0 } ]
如果我做以下事情:
var query=mongoose.model('Employee').find();
query.populate('_department','name');
query.exec(function(err,data){
console.log(data);
});
我得到了这个输出
[ { _department: { _id: 532c77c3485925d806436981, name: 'bar' },
name: 'mimimi',
email: 'email@email.com.br',
_id: 532e570864803bf505e51c81,
__v: 0 } ]
是什么让我想知道选择正在打破填充。 我的猫鼬版本是3.8.8
答案 0 :(得分:5)
当然,您只需指定fields you want即可。目前你只有"电子邮件"所以你得到的就是:
var query=mongoose.model('Employee').find();
query.select('email _department').populate('_department','name');
query.exec(function(err,data){
console.log(data);
});
答案 1 :(得分:0)
在mongoose中为我工作,这里的company_name字段正在通过引用填充 ModelName.find()。populate('parent_id','company_name') .select('username mobile firstname lastname company_name');
答案 2 :(得分:0)
试试我的代码:
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);
});
会为你效劳!