0

我仍在努力解决 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}
}) 
4

1 回答 1

3

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

于 2013-03-31T14:29:13.657 回答