首页 > 解决方案 > Mongoose 不会产生结果,但 mongo shell 会

问题描述

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

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

标签: javascriptmongodbmongooserobo3t

解决方案


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

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

推荐阅读