Mongoose:在查询条件中对模式字段应用函数

在MySQL中,可以在where子句中的一个字段上应用本地函数。 例如。

SELECT * FROM t WHERE DATE(the_date) < '2012-11-19'; 

要么

 SELECT * FROM t WHERE a+b < 20; 

现在,有可能使用mongoose查询条件字段上的函数吗? 假设我正在查询这样的内容:

 tSchema.find({a+b: {$lt: 20}}, callback); 

不,你不能用find来创build计算列,所以你不得不使用aggregate这个更灵活,但也更慢。

喜欢这个:

 tSchema.aggregate([ // Include the a, b, and a+b fields from each doc { $project: { a: 1, b: 1, sum: {$add: ['$a', '$b']}}}, // Filter the docs to just those where sum < 20 { $match: {sum: {$lt: 20}}} ], function(err, result) { console.log(result); }); 

为了完整性,我应该注意到,你可以用find$wherefilter来做到这一点,但是它的性能很糟糕,所以不build议这样做。 像这样:

 tSchema.find({$where: 'this.a + this.b < 20'}, function(err, result) { console.log(result); });