猫鼬选择与填充不工作



我正在mogoose中进行查询,如果我在查询选择上添加任何参数,则填充参数丢失,例如我有以下模式:

部门:

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

当然您只需指定您想要的字段。目前你只有"email",所以你只能得到:

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

试试我的代码:

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);
    });

将为你工作!

在mongoose中为我工作,这里company_name字段正在通过引用填充ModelName.find()。填充("parent_id"、"company_name").select('username mobile firstname lastname company_name');

相关内容

  • 没有找到相关文章

最新更新