【问题标题】:Filter array with Model.find() Mongoose使用 Model.find() Mongoose 过滤数组
【发布时间】:2020-08-11 18:03:06
【问题描述】:

我有一个 mongoose 模型,其中一个字段是日期数组,我需要查询集合以查找该数组中日期介于过去 7 天之间的任何文档,但是当我尝试使用 $gt或 $gte 它不会返回我的文件,即使存在(我已经检查了文件是否存在)。

Here it is an example of the object

它不应该返回超过 7 天的对象。

这是我正在使用的代码:

const { subDays } = require("date-fns");
const mongoose = require("mongoose");
const Journey = require("./models/Journey");
const url = "my-db-url";

mongoose.set("useNewUrlParser", true);
mongoose.set("useUnifiedTopology", true);
mongoose.set("useCreateIndex", true);
mongoose.set("useFindAndModify", false);

mongoose.connect(url, (err) => {
  if (err) throw err;

  console.log("Mongoose connected");
});

Journey.find({
  hospital: "5e6fc0d98db5810012aeb8fe",
  active: false,
  timestampStart: {
    $gte: subDays(new Date(), 7)
  }
})
  .lean()
  .exec((err, journeys) => {
    if (err) throw err;

    console.log(journeys[0]);
  });

旅程模型:

const { Schema, model } = require("mongoose");

const JourneySchema = new Schema(
  {
    tag: {
      type: Schema.Types.ObjectId,
      required: true,
      ref: "Tag",
    },
    patient: {
      type: Schema.Types.ObjectId,
      required: true,
      ref: "Patient",
    },
    hospital: {
      type: Schema.Types.ObjectId,
      required: true,
      ref: "Hospital",
    },
    department: {
      type: [String],
      required: true,
    },
    timestampStart: {
      type: [Date],
      required: true,
    },
    timestampEnd: {
      type: [Date],
      required: true,
    },
    active: {
      type: Boolean,
      default: true,
    },
    rssi: {
      type: [String],
      required: true,
    },
  },
  {
    timestamps: true,
  }
);

module.exports = model("Journey", JourneySchema);

谁能帮我建立这个过滤器?

【问题讨论】:

  • 您拥有的$gte 过滤器似乎应该适用于日期。我确实注意到示例文档不包含名为active 的字段。尝试过滤active: {$ne: true} 而不是active: false,这样当活动字段丢失时它也会匹配
  • 不错,感谢您的建议。活动字段丢失是因为我使用 select 函数将其删除,但是当我在这里发布时忘记将其添加到查询代码中。

标签: node.js mongodb mongoose


【解决方案1】:

日期查询似乎工作得很好。我认为问题出在医院和活动钥匙上。在您提供的示例对象中,两者都缺失。您可以通过删除查询中的这些键或将它们添加到集合中来检查它吗?

【讨论】:

  • 哦,它们不见了,因为我已经用 select 功能排除了它,但忘记在此处添加查询代码,但我发现了错误,它在数据库中,有些日期是错误的。无论如何,感谢您的帮助!
猜你喜欢
  • 2015-02-07
  • 2018-03-20
  • 2021-10-22
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 2019-07-19
  • 2016-06-28
  • 2016-06-20
相关资源
最近更新 更多