Mongoose find inside nested schema

In Mongoose, we explore deeply within a nested schema without much success. Every time we run this function, we always get an empty array.

function findAlarms(lastUpdate = new Date(0), record = Record) {

  // For docs on find http://mongoosejs.com/docs/queries.html
  return record
    .find({
      // Date due must be less than "now"
      'documents.alarm.date_due': {
        $lte: Date.now(),
      },
      // Must be greater than the last update and less than "now"
      'documents.alarm.date_reminder.reminder': {
        $gte: lastUpdate,
        $lte: Date.now(),
      },
    })
    .populate('documents')
    .exec();
}

      

Our diagrams, generally generalized, are as follows:

const RecordSchema = new mongoose.Schema({
  documents: [
    {
      type: Schema.Types.ObjectId,
      ref: 'Document',
    },
  ],
});

      

And our document schema, similarly summarized, looks like this:

const DocumentSchema = new mongoose.Schema({
  alarm: {
    date_due: { type: Date },
    date_reminder: [
      {
        reminder: { type: Date },
      },
    ],
  },
});

      

This search does not show matching items, although we know there are documents that match. If we change our method findAlarms

to use the document schema:

function findAlarms(lastUpdate = new Date(0), document = Document) {
  // For docs on find http://mongoosejs.com/docs/queries.html
  return document
    .find({
      // Date due must be less than "now"
      'alarm.date_due': {
        $lte: Date.now(),
      },
      // Must be greater than the last update and less than "now"
      'alarm.date_reminder.reminder': {
        $gte: lastUpdate,
        $lte: Date.now(),
      },
    })
    .exec();
}

      

He will return all of our relevant documents. However, having records is essential to our needs. Now I can use a hack and then find records using the array document._id

that is returned.

However, I would be interested to know if there is an approach where we can use records directly, since adding this extra step seems really hacky and this operation is done every 5 minutes, so I would like to be more efficient wherever it is possibly,

+3


source to share





All Articles