【问题标题】:Mongoose casting issue when using two fields in a where clause在 where 子句中使用两个字段时的 Mongoose 转换问题
【发布时间】:2013-03-31 23:18:14
【问题描述】:

我仍在尝试解决 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}
}) 

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    要将查询中的一个字段与另一个字段进行比较,您必须使用$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 需要执行的文档数量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-31
      • 2022-11-01
      • 2021-05-18
      • 1970-01-01
      • 2017-12-28
      • 2011-04-22
      • 2019-07-03
      • 1970-01-01
      相关资源
      最近更新 更多