在where子句中使用两个字段时出现猫鼬类型转换问题

Mongoose casting issue when using two fields in a where clause

本文关键字:字段 问题 类型转换 两个 子句 where      更新时间:2023-09-26

我仍然试图围绕mongoDB/mongoose包装我的头,并没有能够锻炼出下面查询的问题;

Link
  .find()
  .where('active').equals(true)
  .where('access_count').gt(0).lte('access_limit')
  .limit(5)
  .sort('-created')
  .exec(function(err,latest)

返回以下强制转换错误;

CastError: Cast to number failed for value "access_limit" at path "access_count"
at SchemaNumber.cast 

这是由.where('access_count').gt(0).lte('access_limit')引起的,我认为这是由于文档上两个字段的比较?是否有一种正确的方法来做这件事,以及对调试这些问题有什么建议?

作为参考,模式定义为;

var LinkSchema = new Schema({
 token: {type: String, unique: true, index: true, required: true }
 , title: {type: String}
 , url: {type: String, required: true}
 , active: {type: Boolean, default: true}
 , created: {type: Date, default: Date.now}
 , access_count: {type: Number, default: 0}
 , access_expiry: Date
 , access_limit: {type: Number, default: 0}
}) 

要在查询中将一个字段与另一个字段进行比较,必须使用$where子句:

Link
  .find()
  .where('active').equals(true)
  .where('access_count').gt(0)
  .$where('this.access_count <= this.access_limit')
  .limit(5)
  .sort('-created')
  .exec(function(err,latest)

$where可能很慢,因此尽可能使用正常的where子句来减少$where需要执行的文档数量。