【问题标题】:Mongoose query returns nothing, while MongoDB query returns expected resultsMongoose 查询不返回任何内容,而 MongoDB 查询返回预期结果
【发布时间】:2018-09-13 06:24:13
【问题描述】:

我正在尝试过滤某个范围内的日期,但我感到非常沮丧,以至于我现在只想查询小于当前时间的日期。

我有这个问题:

q = { 'recorded_timestamp': { '$lt': '2018-09-12T21:02:05.187Z' } };

我也尝试了以下查询,但都不起作用:

q2 = { 'recorded_timestamp': { '$lt': new Date() } };
q3 = { 'recorded_timestamp': { '$lt': new Date(Date.now()) } };
q4 = { 'recorded_timestamp': { '$lt': new Date().toISOString() } };

当我尝试执行MyModel.find(q) 时,我什么也得不到。但是,如果我将该查询完全复制到 MongoDB shell 中,我会得到我期望的结果。

const promise = new Promise(resolve => {
  const results = MyModel.find(q)
  resolve(results);
});
return promise.then(results => {
  return results; // results = [], but they shouldn't
});

这是怎么回事?

  • 猫鼬版本:4.13.14
  • MongoDB 版本:3.4.17
  • 节点版本:8.11.2

以下是该模型的相关摘录:

const MySchema = new Schema({
  some_ID: {
    type:     String,
    required: true
  },
  recorded_timestamp: {
    type:     Date,
    required: true
  }
}, { timestamps: true });

module.exports = mongoose.model('MyModel', MySchema);

这是插入到集合中的示例数据的 sn-p。

{ "some_ID": "16499", "recorded_timestamp": "2007-03- 13T07:39:52.959057" }
{ "some_ID": "17158",  "recorded_timestamp": "2007-09- 12T15:31:18.244142" }

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您需要使用回调来查看结果。

    MyModel.find(q, function(err, result) {
        if (err) {console.log(err);}
        console.log(result);
    })
    

    【讨论】:

    • 是的,我正在这样做。我只是展示了查询的样子。不过,谢谢。我将编辑我的问题以证明我正在这样做。
    【解决方案2】:

    事实证明,插入一堆示例数据的大型 JSON 文件将值存储为字符串(这就是为什么 q = { 'recorded_timestamp': { '$lt': '2018-09-12T21:02:05.187Z' } } 在 MongoDB shell 中执行时有效。)

    我将架构中的“recorded_timestamp”类型更改为字符串,现在它可以工作了。

    这个帖子帮助我诊断了我的问题:Mongoose Queries on Date Condition Have No Results, MongoDB Shell Works

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-10
      相关资源
      最近更新 更多