首页 > 解决方案 > 从对象数组中想要使用 mongoose 获取日期范围明智的数据

问题描述

从对象数组中想要使用 mongoose 获取日期范围明智的数据。

这是我的代码:

sessionSlot.aggregate([
        {
          "$match": {
            'userID': loginUser._id,
            'sessions':  { "date": { "$gte": req.body.from, "$lt": req.body.to } } 
          },
        },
        {$unwind: "$sessions" },
        {
          "$project": {
            "sessions": {
              "$filter": {
                "input": "$sessions",
                "as": "s1",
                "cond": {
                  "$and": [
                    { "$gte": [ "$$s1.date", new Date(req.body.from) ]},
                    { "$lt": [ "$$s1.date", new Date(req.body.to) ]}
                  ]
                }
              }
            }
          }
        }
      ], (err, result) => {
        console.log('..........', result);
      })

这是我的架构:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');

var sessionSlotSchema = mongoose.Schema({

    userID      : { type: String },
    mail        : { type: String },
    slotFlag    : { type: Boolean },
    slotID      : { type: String },
    slotType    : { type: String },
    sessions    : [{
                    date         : { type: String, default:null },
                    userID       : { type: String, default:null },
                    therapyType  : { type: String, default:null },
                    price        : { type: String, default:null },
                    startDate    : { type: String, default:null },
                    totalSession : { type: String, default:null },
                    status       : { type: String, default:'empty' },
                    profilepic   : { type: String, default:null },
                    fullname     : { type: String },
                    autoBook     : { type: Boolean, default:false },
                    time         : { type: String, default:null },
                    duration     : { type: String, default:null },
                    reminders    : { type: String, default:null }
    }]
})

module.exports = mongoose.model('sessionSlot', sessionSlotSchema, 'sessionSlot');

我收到类似 MongoError 的错误:异常:无效运算符“$filter”。那么我错在哪里了?

我在请求正文中以日期格式传递两个日期。req.body.from 和 req.body.to 是我想要数据的两个字段。

标签: javascriptnode.jsmongodbexpressmongoose-schema

解决方案


推荐阅读