Mongodb中的子文档的查询集合返回错误的数据

时间:2017-08-11 01:01:08

标签: mongodb mongoose nodes

我需要在包含子文档数组的集合('Model:Ag_escalaatendimento')中运行查询,并仅返回范围日期中的文档。

我的问题是我的查询是返回日期超出范围的文档。

我做错了什么?

//架构

const agEscalaAtendimentosSchema = new mongoose.Schema({
  ativo:{type:Boolean},
  profissional:{type:mongoose.Schema.Types.ObjectId, ref:'Profissional'},
  horarios_gerados:[{date_atd:{di:{type:Date}, df:{type:Date}},situacao:{type:Number, default:1}}],
});

module.exports = mongoose.model('Ag_escalaatendimento', agEscalaAtendimentosSchema,'ag_escalaatendimentos' );

const profissionaisSchema = new mongoose.Schema({
  nome: {type: String,required:true},
  cpf: {type: String},
},{ toJSON: { virtuals: true } });
module.exports = mongoose.model('Profissional', profissionaisSchema,'profissionais' );

//查询

  var qry={ profId: '593c838ad32a453b538b1a72',
  dataInicio: '2017-08-11T00:42:05.575Z',
  dataFim: '2017-08-26T00:42:05.575Z' }

  var qrySearch={"_id": new ObjectId(qry.profId)}
  var di=new Date(qry.dataInicio);
  var df=new Date(qry.dataFim);

  Profissional.find(qrySearch)
    .exec( (err,data) => {
        var p1;
        var p=[];
        for (var i = 0, len = data.length; i < len; i++) {
              var id=data[i]._id;
              p1=Ag_escalaatendimento.find({'profissional':id, 'horarios_gerados':{ $elemMatch:{'date_atd.di':{$gte:di},'date_atd.df':{$lte:df}} }}).exec();
              p.push(p1);
        }
        Promise.all(p).then((response)=>{
           var h1=response[0]; //array
           h1.forEach( (item)=>console.log(item.horarios_gerados.slice(0,3)))
        }, (error)=>{
           console.log(error);
          }
        )
    })

//错误的结果

  [ { date_atd: { df: 2017-01-02T12:00:00.000Z, di: 2017-01-02T10:00:00.000Z },
    situacao: 1,
    _id: 598cf1b7b16a301abcb5661d },
  { date_atd: { df: 2017-01-02T18:00:00.000Z, di: 2017-01-02T16:00:00.000Z },
    situacao: 1,
    _id: 598cf1b7b16a301abcb5661c },
  { date_atd: { df: 2017-01-03T12:00:00.000Z, di: 2017-01-03T10:00:00.000Z },
    situacao: 1,
    _id: 598cf1b7b16a301abcb5661b } ]

0 个答案:

没有答案