【问题标题】:Mongoose does not produce a result but mongo shell doesMongoose 不会产生结果,但 mongo shell 会
【发布时间】:2021-06-18 22:08:00
【问题描述】:

我有产品架构,其中有一个字段 storeZones 对象定义为

...
storeZones: {
  type: {
    masterZone: {type: Schema.Types.ObjectId, model: 'Zone', index: 1 },
    zone: { type: Schema.Types.ObjectId, model: 'Zone', index: 1 },
    subZone: { type: Schema.Types.ObjectId, model: 'Zone', index: 1 },
    },
    default: {
      masterZone: null,
      zone: null,
      subZone: null,
    },
  },
...

我正在计算特定 masterZone 中的产品。所以我的查询是

const condition = { 'storeZones.masterZone': masterZone };

console.log(condition); // { 'storeZones.masterZone': '60533e6a745d465ab6cb3fc9' }

const total = await Product.count(condition);

这将返回 0 个结果。 但是当我将确切的查询粘贴到 mongo shell 中时;确切地说是Robo3t。

db.products.find({'storeZones.masterZone': ObjectId('60533e6a745d465ab6cb3fc9') } )

它产生所需的输出。有人可以提供一些帮助吗?

【问题讨论】:

  • 通过手动将猫鼬查询中的 masterZone 从 string 转换为 ObjectId 来修复它。奇怪的是,我不得不手动执行此操作,因为 mongoose 自己执行此操作,因为我已将 masterZone 定义为 ObjectId。

标签: javascript mongodb mongoose robo3t


【解决方案1】:

通过将 masterZone 从请求转换为 ObjectId 来修复它。不知道为什么我需要这样做,但这解决了它!所以...

  const m = mongoose.Types.ObjectId(masterZone);
  const condition = { 'storeZones.masterZone': m };
  console.log(condition); // { 'storeZones.masterZone': '60533e6a745d465ab6cb3fc9'}
  const total = await Product.count(condition);   

【讨论】:

    猜你喜欢
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多