javascript - 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') } )
它产生所需的输出。有人可以提供一些帮助吗?
解决方案
通过将masterZone
from 请求转换为ObjectId
. 不知道为什么我需要这样做,但这解决了它!所以...
const m = mongoose.Types.ObjectId(masterZone);
const condition = { 'storeZones.masterZone': m };
console.log(condition); // { 'storeZones.masterZone': '60533e6a745d465ab6cb3fc9'}
const total = await Product.count(condition);
推荐阅读
- sql-server - 重叠日期时间的触发器
- spring - 找不到名为“entityManagerFactory”的bean
- android - 如何从其他活动中调用此功能?
- javascript - 使用 Array.includes() 和测试重复项的 JavaScript 问题
- python - np.argsort() 的奇怪/错误输出
- javascript - 我可以在 TypeScript 中只使用 null(而不是 undefined)吗?
- testing - 如何使用@BeforeClass 使方法运行多次?
- mysql - MySQL 8 更新、设置、案例
- html - 左边为零的嵌套粘性元素不粘性
- reactjs - React / Ant Design - 无法上传 XLSX