Получить результаты запроса агрегации в mongoose, используя objectId, виртуальные типы (работает в оболочке mongo) - PullRequest
0 голосов
/ 07 октября 2019

Мой код на сервере, на случай, если он имеет значение (NodeJS и MogoDB):

//my includes at the top of the file
const mongoose = require('mongoose');
const Appt = mongoose.model('Appt');
const ApptType = mongoose.model('ApptType');
const ApptStatus = mongoose.model('ApptStatus');
var moment = require('moment-timezone');
moment().tz('America/New_York');
now = moment(); // add this 2 of 4
dayStart = now.startOf('day');
dayEnd = now.endOf('day');

// the aggregation query that's not returning correctly
Appt.aggregate([
      {
        $match: {
          patientID: appt.patientID._id,
          scheduled: {
            $gte: new Date(start),
            $lt: new Date(appt.pmtduedate)
          }
        }
      },
      {
        $group: {
          _id: 'id',
          payment: { $sum: '$payment' },
          pmtdue: { $sum: '$pmtdue' },
          visits: { $sum: 1 }
        }
      }
    ]).exec(
      err => {
        console.log(`Error finding past payments`, err);
        callback(err);
      },
      result => {
        console.log(`RESULT: ${result}`);
        pastPayments = result;
        if (!pastPayments || pastdueamt === 0) {
          pastdueamt = 0;
          console.log(`2.  getCurrentDue ${pastdueamt}`);
          this.getCurrentDue(appt, pastdueamt, today, callback);
        } else {
          console.log(`pastPayments ${pastPayments}`);
          console.log(
            `planamt ${planamt} pmtdue ${pastPayments.pmtdue} payments: ${pastPayments.payment}`
          );
          pastdueamt =
            pastPayments.pmtdue === 0
              ? planamt - pastPayments.payment
              : pastPayments.pmtdue - pastPayments.payment;
          console.log(`pastdueamt calculated: ${pastdueamt}`);
          console.log(`2.  getCurrentDue`);
          this.getCurrentDue(appt, pastdueamt, today, callback);
        }
      }
    );

Когда я запускаю свой запрос в монго, ожидаемые результаты возвращаются. В моем приложении результаты этого запроса ничего не возвращают (также без ошибок). Я попытался сделать следующее:

$match: {
    patientID: new mongoose.types.ObjectId(appt.patientID._id),

Я также попробовал:

$match: {
    patientID: { $toObjectId: appt.patientID._id },

, но я получаю ошибки в обоих этих вариантах. Первый возвращает ошибку TypeError: Cannot read property 'ObjectId' of undefined. Вторая возвращает какую-то ошибку Монго errmsg: 'unknown operator: $toObjectId', code: 2, codeName: 'BadValue', name: 'MongoError', [Symbol(mongoErrorContextSymbol)]: {} }

Как мне успешно выполнить агрегацию Мангуста с использованием идентификаторов объектов, виртуальных типов и т. Д.?

ИЗМЕНЕНО ДЛЯ ДОБАВЛЕНИЯ МОЕЙ СХЕМЫ:

const apptSchema = new mongoose.Schema(
  {
    ID: Number,
    patientID: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Patient'
    },
    oldPatientID: Number,
    status: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'ApptStatus'
    },
    type: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'ApptType'
    },
    scheduled: Date,
    note: String,
    reminder: Boolean,
    cell: Boolean,
    email: Boolean,
    subjective: String,
    assessment: String,
    plan: String,
    planamt: Number,
    objective: {
      clearUC: Boolean,
      UCcheck: String,
      thompson: String,
      activator: String,
      other: String
    },
    updated: {
      type: Date,
      default: new Date()
    },
    pmtdue: Number,
    pmtduedate: Date,
    payment: Number,
    pmttype: String,
    paid: Boolean,
    pmtnote: String
  },
  { toJSON: { virtuals: true } }
);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...