Mongoose 不会产生结果,但 mongo shell 会产生结果

时间:2021-03-22 09:07:52

标签: javascript mongodb mongoose robo3t

我有产品架构,其中有一个字段 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') } )

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

1 个答案:

答案 0 :(得分:0)

通过将 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);